3.8. String Immutable

3.8.1. Rationale

  • str is immutable

  • str methods create a new modified str

>>> a = 'Python'
>>> a.replace('P', 'C')
'Cython'
>>> print(a)
Python
>>> a = 'Python'
>>> b = a.replace('P', 'C')
>>>
>>> print(a)
Python
>>> print(b)
Cython
>>> a = 'Python'
>>> a = a.replace('P', 'C')
>>>
>>> print(a)
Cython

3.8.2. Memory

../../_images/str-memory-1.png
../../_images/str-memory-2.png
../../_images/str-memory-3.png
../../_images/str-immutable.png

3.8.3. Value Check

This is valid way to check str value:

>>> name = 'Mark Watney'
>>> name == 'Mark Watney'
True

The following code will produce SyntaxWarning due to the invalid operand <input>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?:

>>> name = 'Mark Watney'
>>> name is 'Mark Watney'
False

3.8.4. Length

>>> len('hello')
5

3.8.5. Concatenation

  • Preferred string concatenation is using f-string formatting

>>> 'a' + 'b'
'ab'
>>> 'a' 'b'
'ab'
>>> data = 'one' \
...        'two' \
...        'three'
>>>
>>> data
'onetwothree'

3.8.6. Concat "Numbers"

>>> 1 + 2
3
>>> '1' + '2'
'12'

3.8.7. Concat Multiply

>>> '*' * 10
'**********'
>>> text = 'Hello world'
>>> print(text + '\n' + '!'*len(text))
Hello world
!!!!!!!!!!!
>>> 'Beetlejuice' * 3
'BeetlejuiceBeetlejuiceBeetlejuice'
>>> 'Mua' + 'Ha' * 2
'MuaHaHa'
>>>
>>> 'Mua' + ('Ha'*2)
'MuaHaHa'
>>>
>>> ('Mua'+'Ha') * 2
'MuaHaMuaHa'

3.8.8. Concat Problem

>>> 'Jan' + 'Twardowski'
'JanTwardowski'
>>> 'Jan' + ' ' + 'Twardowski'
'Jan Twardowski'
>>> 'Jan Twardowski'
'Jan Twardowski'

3.8.9. Use Case - 0x01

>>> firstname = 'Jan'
>>> lastname = 'Twardowski'
>>>
>>> firstname + lastname
'JanTwardowski'
>>> firstname = 'Jan'
>>> lastname = 'Twardowski'
>>>
>>> firstname + ' ' + lastname
'Jan Twardowski'
>>> firstname = 'Jan'
>>> lastname = 'Twardowski'
>>>
>>> f'{firstname} {lastname}'
'Jan Twardowski'

3.8.10. Use Case - 0x02

>>> firstname = 'Jan'
>>> lastname = 'Twardowski'
>>>
>>> 'Hello ' + firstname + ' ' + lastname + '!'
'Hello Jan Twardowski!'
>>> firstname = 'Jan'
>>> lastname = 'Twardowski'
>>>
>>> f'Hello {firstname} {lastname}!'
'Hello Jan Twardowski!'

3.8.11. Assignments