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!

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()