Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Merge Multiple Strings

Python Merge Multiple Strings

Document Object Reference Manual Python3 Examples

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

Example

Define multiple strings

str1

=

"Hello"

str2

=

"World"

str3

=

"!"

Merge strings using the plus sign

combined_str1

=

str1 +

" "

Merge strings using the join() method

combined_str2

=

" "

.

join

(

[

str1

,

str2

]

)

Merge using formatted strings

combined_str3

=

f

"{str1} {str2}{str3}"

Output result

print

(

combined_str1

)

print

(

combined_str2

)

print

(

combined_str3

)

Code analysis:

  1. str1, str2, str3 are the three strings to be merged.
  2. combined_str1 Use the plus sign + to concatenate the strings, adding a space in between.
  3. combined_str2 Use join() method joins the elements in the string list together, and then adds str3。
  4. combined_str3 Use formatted strings f"" to embed variables directly into the string.

Output result:

Hello World!
Hello World!
Hello World!

Document Object Reference Manual Python3 Examples