Python Concatenate Multiple Strings

Document 对象参考手册Python3 Examples

In Python, concatenating multiple strings can be achieved in multiple ways, including using the plus sign+、join()method or formatted strings. Below we will demonstrate how to concatenate multiple strings with a simple example.

Example

# Define multiple strings
str1 = "Hello"
str2 = "World"
str3 = "!"

# Concatenate strings using the plus sign
combined_str1 = str1 + " " + str2 + str3

# Concatenate strings using the join() method
combined_str2 = " ".join([str1, str2]) + str3

# Concatenate using formatted strings
combined_str3 = f"{str1} {str2}{str3}"

# Output the result
print(combined_str1)
print(combined_str2)
print(combined_str3)

Code Analysis:

  1. str1, str2, str3are the three strings to be concatenated.
  2. combined_str1Using the plus sign+concatenates the strings together, with a space added in between.
  3. combined_str2Usingjoin()method joins the elements in the string list together, and then addsstr3。
  4. combined_str3Using formatted stringsf""embeds the variables directly into the string.

Output result:

Hello World!
Hello World!
Hello World!

Document 对象参考手册Python3 Examples

Other Extensions