Learning Python basics through questions is a fantastic way to grasp the fundamentals of Python programming. This article delves into String Basics, explaining that Python strings are collections of characters enclosed in single, double, or triple quotes. We’ll explore indexing and slicing, where string indexing begins at 0, and reverse indexing starts from -1. Remember, Python strings are immutable, but you can create new strings by reassigning variables. Internally, characters are stored as binary streams, encoded using ASCII or Unicode. Furthermore, we’ll discuss accessing individual characters, known as string slicing, using square brackets that hold the index or reverse index.
One can understand the python strings will the help of following short description:
The following code demonstrates different syntaxes for creating string variables in Python. Here’s a brief explanation of each syntax:
#Syntax:
str_var="your string"
str_var='your string'
str_var='''your strng'''
# Example-1: #Using single quotes
str1 = 'Ezy Learning'
print(str1)
# Example-2: Using double quotes
str2 = "Ezy Learning"
print(str2)
# Example-3: #Using triple quotes
str3 = '''''Python string is the collection
of the characters surrounded
by single quotes,
double quotes, or triple
quotes'''
print(str3)
Ezy Learning
Ezy Learning
''Python string is the collection
of the characters surrounded
by single quotes,
double quotes, or triple
quotes
Like other languages, the indexing of the Python strings starts from 0.
For example, The string “HELLO” is indexed as given in the below figure
Like other languages, Python string indexing starts at 0.
For example, the string “HELLO” is indexed as shown below.
my_string[0]
. This would return the character “H”.my_string[0:3]
. This would return the string “HEL”.# Define a string variable
my_str = 'HELLO'
# Use a try-except block to handle potential index out of range error
try:
# Print each character of the string
print(my_str[0])
print(my_str[1])
print(my_str[2])
print(my_str[3])
print(my_str[4]) # This line will cause an index out of range error
print(my_str[5]) # This line will not be executed due to the error in the previous line
print(my_str[6]) # This line will not be executed due to the error in the previous line
# Catch any exception that occurs and print the error message
except Exception as e:
print(e)
H
E
L
L
O
string index out of range
`except Exception as e:` – This block catches any exception that occurs within the `try` block and assigns it to the variable `e`. 10. `print(e)` – This line prints the exception that occurred, which in this case would be an IndexError due to attempting to access an index that is out of range for the string.
## Example
# Given String
str = "EzyLearning.in"
# Start Oth index to end
print(str[0:]) #--> EzyLearning.in
# Starts 1th index to 4th index
print(str[1:5]) #--> zyLe
# Starts 2nd index to 3rd index
print(str[2:4]) #--> yL
# Starts 0th to 2nd index
print(str[:3]) #--> Ezy
#Starts 4th to 6th index
print(str[4:7]) #--> ear
EzyLearning.in
zyLe
yL
Ezy
ear
# apply slicing
print(str[4:4])
## this will give no results.... please share your view for this question in the comment section.
## this will give no results (i.e. empty string) .... please share your view for this question in the comment section.
Fail to find the cause, No issues, just read the following:
The selected code `print(str[4:4])` attempts to print a substring of the variable `str` from index 4 to index 4. However, this will result in an empty string being printed, as the start and end indices are the same. In Python, when slicing a string, the start index is inclusive, and the end index is exclusive. Therefore, in the python strings, when the start and end indices are the same, an empty string is returned.
# Accessing the last character of the string
print(str[-1])
# Accessing the third character from the end of the string
print(str[-3])
# Accessing the last two characters of the string
print(str[-2:])
# Accessing a substring from the fourth character from the end to the second character from the end
print(str[-4:-1])
# Accessing a substring from the seventh character from the end to the third character from the end
print(str[-7:-2])
g
n
ng
rnn
Learn
# Reversing the given string
print(str[::-1]) # Print the string in reverse order
print(str[-8:-2]) # Print a substring of the string from index -8 to -3
gnnraeLyzE
yLearn
# This line of code prints a substring of the string 'str' starting from index 4 (exclusive) and ending at index 2 (inclusive) in reverse order.
print(str[4:2:-1])
eL
a. Strings are immutable in Python.
b. A string can only be replaced with new string since its content cannot be partially replaced.
c. Updating the content of the strings is as easy as assigning it to a new string.
d. The string object doesn’t support item assignment i.e., partial updation not allowed but total replacement is allowed
# Define a string variable
string = "HELLO"
try:
# Attempt to modify the first character of the string
string[0] = "h"
print(string)
except Exception as e:
# If an exception occurs, print the error message
print(e)
Output:
'str' object does not support item assignment
`str = "HELLO"`
– This line initializes a string variable `str` with the value “HELLO”. `try:`
– This keyword marks the beginning of a block of code where an exception might occur.
`str[0] = "h"`
– This line attempts to modify the first character of the string `str` from ‘H’ to ‘h’. This operation will raise an error because strings in Python are immutable. print(str)`
– This line prints the modified string. However, since the modification will raise an error, this line will not be executed. `except Exception as e:`
– This block catches any exception that occurs within the `try` block and assigns it to the variable `e`. `print(e)`
– This line prints the exception that occurred, which in this case will be “TypeError: ‘str’ object does not support item assignment”.# Set the value of the variable str to "HELLO"
str = "HELLO"
# Print the value of str
print(str)
# Set the value of the variable str to "hello"
str = "hello"
# Print the value of str
print(str)
# Output:
HELLO
hello
The above code snippet contains two lines of code:
a. As we know that strings are immutable. We cannot delete or remove the characters from the string.
b. But we can delete the entire string using the del keyword.
## partial deletion not allowed, will give and error : TypeError: 'str' object doesn't support item deletion
str = " EzyLearning " ## Define a string variable
try:
del str[1] ## Try to delete a character at index 1, which is not allowed for strings
except Exception as e:
print(e) ## Print the exception message if deletion is not allowed
# Output:
'str' object doesn't support item deletion
The given code initializes a variable `str1` with the value “EzyLearning”, then deletes the variable using the `del` keyword and attempts to print the value of `str1`.
However, since the variable has been deleted, an error will occur when trying to print `str1`.
# The selected code attempts to delete the variable 'str1' and then print its value, which should result in an error since the variable has been deleted.
str1 = "EzyLearning" # Create a new string variable
del str1 # Delete the variable 'str1'
# Attempt to print the value of the deleted variable, which should raise an exception
try:
print(str1)
except Exception as e:
print(e) # Print the exception message if an exception occurs
# Output:
name 'str1' is not defined
All about java servlets Part-2 What is a website? Website is a collection of related…
Let's train the machine. Machine learning is a growing technology which enables computers to learn…
“Unless you try to do something beyond what you have already mastered, you will never…
Whenever you decide to start coding and you want to become budding coder or programmer…
C components are essential elements of a C program, including comments, preprocessor directives, functions, statements,…
All about java servlets Part-2 What is a website? Website is a collection of related…