Strings in Python
Strings in Python are immutable arrays of characters.
Accessing characters
s = "Hello"
s[1]
'l'
s = "Hello"
s[-1]
'o'
Immutability
Immutability means that the content of the object cannot change.
s = "Hello"
s[1] = "a"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[3], line 2
1 s = "Hello"
----> 2 s[1] = "a"
TypeError: 'str' object does not support item assignment
However, a variable can be reassigned.
s = "Hello "
s = s + "ENS Lyon!"
print(s)
Hello ENS Lyon!
Reasons
Here are reasons why strings are immutable in Python:
- They are used as hash values in hashtables
- To avoid side-effects (e.g. being modified by functions)
- For allowing optimisation e.g. String Interning (several
"hello"all points to the same object) - For avoid race conditions in multi-thread applications
Multiple assignments
s = ""
for i in range(10000000):
s += f"entier {i};"
L = [f"entier {i};" for i in range(10000000)]
''.join(L)
import io
ss = io.StringIO()
for i in range(10000000):
ss.write(f"entier {i};")
s = ss.getvalue()