Sobes.tech
Junior

What are the ways to concatenate strings in Python?

sobes.tech AI

Answer from AI

  1. Concatenation using the + operator.
  2. Joining with the .join() method.
  3. Formatted string literals (f-strings).
  4. The % string formatting operator (deprecated).
# 1. Operator +
s1 = "Hello"
s2 = "World"
result1 = s1 + " " + s2
# 2. Method .join()
words = ["Hello", "World"]
result2 = " ".join(words)
# 3. F-strings
name = "World"
result3 = f"Hello {name}"
# 4. Operator % (deprecated)
name = "World"
result4 = "Hello %s" % name

The .join() method is the most efficient for concatenating a large number of strings, as it creates a new string only once, whereas the + operator creates intermediate strings on each iteration. F-strings are the recommended method for formatting because they are more readable and performant than the % operator.