Sobes.tech
Junior

How does string multiplication work in Python?

sobes.tech AI

Answer from AI

String multiplication in Python results in concatenating the string with itself a specified number of times. If the multiplier is zero or a negative number, the result is an empty string.

# Multiplying a string by a positive number
s = "abc"
result_positive = s * 3 # result_positive will be "abcabcabc"
print(result_positive)

# Multiplying a string by zero
result_zero = s * 0 # result_zero will be ""
print(result_zero)

# Multiplying a string by a negative number
result_negative = s * -2 # result_negative will be ""
print(result_negative)

# Multiplying a string by a non-integer will cause a TypeError
# try:
#     s * 1.5
# except TypeError as e:
#     print(e) # Will output "can't multiply sequence by non-int of type 'float'"

Working principle:

  1. Python checks the type of the multiplier. If it is not an integer (int), a TypeError occurs.
  2. If the multiplier is an integer:
    • If the multiplier is greater than zero, a new string is created, which is the result of repeating the original string.
    • If the multiplier is less than or equal to zero, an empty string "" is returned.

This operation creates a new string copy. The original string remains unchanged.