Back to course

String Concatenation and Repetition

Python Programming: The 0 to Hero Bootcamp

Combining Strings

Concatenation (+ Operator)

You can join two or more strings together using the + operator. You must ensure all elements being joined are strings.

python first = 'Hello' second = 'World'

Adding a space for readability

greeting = first + ' ' + second + '!' print(greeting) # Output: Hello World!

age = 25

Fails because age is an int: my_info = 'I am ' + age + ' years old'

Correct way using casting:

my_info = 'I am ' + str(age) + ' years old' print(my_info)

String Repetition (* Operator)

The multiplication operator (*) can be used to repeat a string a specified number of times.

python star_line = '*' * 15 print(star_line) # Output: ***************

error_message = 'ERROR! ' * 3 print(error_message) # Output: ERROR! ERROR! ERROR!

Immutability of Strings

Strings in Python are immutable. Once created, they cannot be changed in place. If you 'modify' a string, Python actually creates a brand new string.

python name = 'Sam'

name[0] = 'P' # This will cause an error (TypeError)

To change it, you must reassign the variable to a new string:

name = 'Pam' print(name) # Output: Pam