SoFunction
Updated on 2024-11-20

Summary of python string concatenation methods

There are many string concatenation methods in python, which are specifically summarized here today:

①. Original string concatenation: str1 + str2
②.python new string concatenation syntax: str1, str2
③. Strange string way: str1 str2
④. % Connection string: 'name:%s; sex: ' % ('tom', 'male')
⑤. String list concatenation: (some_list)

The following is a specific analysis:

The first, as anyone with programming experience is probably aware, is to directly concatenate two strings with "+":

'Jim' + 'Green' = 'JimGreen'

The second is more specific, if two strings are separated by a "comma" then the two strings will be concatenated, however, there will be an extra space between the strings:

'Jim', 'Green' = 'Jim Green'

The third, also unique to python, is to put two strings together, with or without whitespace: the two strings are automatically concatenated into a single string:

'Jim''Green' = 'JimGreen'
'Jim' 'Green' = 'JimGreen'

The fourth is more powerful and borrows from the printf function in C. If you have a basic knowledge of C, read the documentation. In this way, the symbol "%" is used to connect a string to a set of variables, and any special marks in the string are automatically replaced by variables in the set of variables on the right:

'%s, %s' % ('Jim', 'Green') = 'Jim, Green'

The fifth one is a trick, using the string function join. This function takes a list and joins each element of the list in turn with a string:

var_list = ['tom', 'david', 'john']
a = '###'
(var_list) = 'tom###david###john'

Actually, there is another way of string concatenation in python, but it's not used much, which is string multiplication, e.g.:

a = 'abc'
a * 3 = 'abcabcabc'

I hope the examples described in this article will help you with your Python programming.