Python provides multiple ways to concatenate one or more strings together. Since Python strings are immutable, a new string will always be generated after string concatenation.
Simple way to connect strings
To concatenate two or more strings, just place them next to each other.
s = 'Hello' 'World' print(s) #Output: HelloWorld
Note that this method does not work with string variables.
Use the "+" operator to connect strings
A direct way to concatenate multiple strings into one string is to use the "+" operator.
s ='Hello' + 'World' print(s)
The "+" operator is suitable for strings and string variables.
s1 = 'Hello' s2 = s1 + 'World' print(s2)
Use the "+=" operator to connect strings
Similar to the "+" operator, multiple strings can be concatenated into one using the "+=" operator.
s = 'Hello' s += 'World' print(s)
Use the join() method to connect strings
The join() method allows concatenation of a string list into a string:
s1 = 'Hello' s2 = 'World' s3 = ''.join([s1, s2]) print(s3)
The join() method also allows specifying a delimiter when connecting a string.
s1 = 'Hello' s2 = 'World' s3 = ' '.join([s1, s2]) print(s3) #Output: Hello World
In this example, the join() method is used to concatenate a string separated by a space.
The following example uses this method to separate strings by commas.
s1, s2, s3 = 'Python', 'Hello', 'World' s = ','.join([s1, s2, s3]) print(s) # Output: Python, Hello, World
Use % to connect string
The String object has a built-in % operator that can be used to format strings, which can be used to concatenate strings.
s1, s2, s3 = 'Python', 'Hello', 'World' s = '%s %s %s' % (s1, s2, s3) print(s)#Output: Python Hello World
Use the format() method to connect strings
You can use the format() method to concatenate multiple strings into one string.
s1, s2, s3 = 'Python', 'Hello', 'World' s = '{} {} {}'.format(s1, s2, s3) print(s)
Use f-strings to connect strings
Python 3.6 introduces f-strings, allowing strings to be formatted in a more concise and elegant way. You can use f-strings to concatenate multiple strings into one string.
s1, s2, s3 = 'Python', 'Hello', 'World' s = f'{s1} {s2} {s3}' print(s)
Which string concatenation method is easier? Although there are several ways to concatenate strings in Python, it is recommended to use the join() method, the "+" operator, and f-strings to concatenate strings.
This is the end of this article about 7 ways to connect strings in Python. For more related Python connection string content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!