5.4. String Immutable

  • str is immutable

  • str methods create a new modified str

>>> text = 'Mark'
>>> result = text.upper()
>>>
>>> print(result)
MARK
>>>
>>> print(text)
Mark

5.4.1. Memory

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

5.4.2. Value Check

  • Use == to check if strings are equal

This is valid way to check str value:

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

5.4.3. Length

  • Builtin len() returns the length of a string

>>> len('Mark')
4

5.4.4. Concatenation

  • Preferred string concatenation is using f-string formatting

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

5.4.5. Concat Problem

>>> firstname = 'Mark'
>>> lastname = 'Watney'
>>>
>>> firstname + lastname
'MarkWatney'
>>>
>>> firstname + ' ' + lastname
'Mark Watney'
>>> firstname = 'Mark'
>>> lastname = 'Watney'
>>>
>>> f'{firstname} {lastname}'
'Mark Watney'

5.4.6. Concat Numbers

>>> 1 + 2
3
>>>
>>> '1' + '2'
'12'
>>>
>>> '1' + 2
Traceback (most recent call last):
TypeError: can only concatenate str (not "int") to str
>>>
>>> 1 + '2'
Traceback (most recent call last):
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> name = 'Mark Watney'
>>> age = 42
>>>
>>> 'Astronaut ' + name + ' is ' + age + ' years old.'
Traceback (most recent call last):
TypeError: can only concatenate str (not "int") to str
>>>
>>> 'Astronaut ' + name + ' is ' + str(age) + ' years old.'
'Astronaut Mark Watney is 42 years old.'
>>>
>>> f'Astronaut {name} is {age} years old.'
'Astronaut Mark Watney is 42 years old.'

5.4.7. Concat Multiply

>>> '*' * 10
'**********'
>>> text = 'Hello world'
>>> print(text + '\n' + '!'*len(text))
Hello world
!!!!!!!!!!!

5.4.8. Use Case - 1

>>> firstname = 'Mark'
>>> lastname = 'Watney'
>>>
>>> 'Hello ' + firstname + ' ' + lastname + '!'
'Hello Mark Watney!'
>>> firstname = 'Mark'
>>> lastname = 'Watney'
>>>
>>> f'Hello {firstname} {lastname}!'
'Hello Mark Watney!'