Complete Guide to Python String
Initialization
str1 = 'Text enclosed with single quotes.'
str2 = "Text enclosed with double quotes."
Access
- The in-operator can be used to check a substring exists in a string.
print("single" in str1) # output: True
- The subscript-operator can be used for accessing a character using the correspoding index. IndexError-exception will be thrown for non-existing indices.
print(str1[2]) # output: x
- The slice-operator [start:], [start:end], [:end]
- Negative integer can be used to start from the last. [-start:], [-start:-end], [:-end]
print(str1[2:7]) # output: xt en
- Iteration through characters.
for c in str1:
print(c)
Update
- You cannot modify a string since it is immutable.
Methods
- str1.format().
msg = "Hello {}!".format("John")
print(msg) # output: Hello John!
- str1.split(delimeter_str).
print(str1.split(" "))
# output: ['Text', 'enclosed', 'with', 'single', 'quotes.']
- str1.replace(search_str, replace_str).
- It won’t modify the existing string but return the modified string.
new_str = str1.replace("enclosed with", "and")
print(new_str) # output: Text and single quotes.
Operators
- Concatenation operator: +
userName = "John"
msg = "Hello " + userName
print(msg) # output: Hello John
- Multiplication operator: *
msg = 3 * "AB"
print(msg) # output: ABABAB
Interview Questions
1. When you access a character using subscript operator, Do you get an element of type character or string?
There is no character type in python. It is a string of length 1.