5.2. String Concatenation

  • str is immutable

  • str methods create a new modified str

  • Concatenation - joining two or more strings

5.2.1. Add

  • You can concatenate using + operator or with f-string

  • Since Python 3.6 f-string concatenation is preferred (it is also faster)

>>> 'Hello' + 'World'
'HelloWorld'
>>>
>>> 'Hello' + ' ' + 'World'
'Hello World'

5.2.2. Implicit Concatenation

  • You can concatenate string literals by placing them next to each other

  • This works only for string literals, not for variables

>>> 'Hello' 'World'
'HelloWorld'
>>>
>>> 'Hello' ' ' 'World'
'Hello World'

5.2.3. Interpolation

  • You can use f-string to embed expressions inside string literals

>>> firstname = 'Alice'
>>> lastname = 'Apricot'
>>> age = 30
>>>
>>> f'User {firstname} {lastname} is {age} years old'
'User Alice Apricot is 30 years old'
>>>
>>> 'User ' + firstname + ' ' + lastname + ' is ' + str(age) + ' years old'
'User Alice Apricot is 30 years old'

5.2.4. Multiply

>>> 'ha' * 3
'hahaha'

5.2.5. Case Study - 1

>>> username = 'alice'
>>> domain = 'example.com'
>>>
>>> username + '@' + domain
'alice@example.com'
>>>
>>> f'{username}@{domain}'
'alice@example.com'

5.2.6. Case Study - 2

>>> header = 'Python Basics'
>>> underline = '*' * len(header)
>>>
>>> print(f'{header}\n{underline}')
Python Basics
*************