Interesting facts about strings in Python

• Immutability
• Auto-detection of escape sequences
• Direct slicing
• Indexed access

Immutability

This means that there is no permission of modification on <string>type and we only have read only access to the strings.

Example

inp = 'Tutorials point'
# output
print(inp)
# assigning a new value to a particular index in a
string
inp[0] = 't'
print(inp) # raises an error

Output

TypeError: 'str' object does not support item assignment

Auto-detection of escape sequences

The strings containing backslash are automatically detected as an escape sequence.

Example

inp = 'Tutorials point'
# output
print(inp+”\n”+”101”)

Output

Tutorials point
101

Direct slicing

We all are aware of substring method in c or c+ +, Slicing does the same operation in python. it takes two compulsory and 1 optional argument. Compulsory arguments are start index (included) and end index(not included) Optional argument is the step or say increment or decement value. By default it is 1.

Example

Live Demo

inp = 'Tutorials point'
# output
print(inp[0:5])

Output

Tutor

Indexed access

As all elements are stored in a contiguous format, therefore we can access elements directly by the help of index.

Example

Live Demo

inp = 'Tutorials point'
# output
print(inp[0]+inp[1])

Output

Tu