Home > Article > Backend Development > Introduction to five methods of python string concatenation
There are many string connection methods in python. I am writing code today. By the way, to summarize, from the most original string connection method to string list connection, everyone feels:
The most original string Connection method: str1 + str2
python New string connection syntax: str1, str2
Strange string method: str1 str2
% Connection string: 'name:%s; sex:%s ' % ('tom', 'male')
String list connection: str.join(some_list)
The first method, anyone with programming experience probably knows it, just use "+ ” to connect two strings:
>>> print('jim'+'green')
jimgreen
The second one is special, if two characters The strings are separated by "comma", then the two strings will be concatenated, but there will be an extra space between the strings:
>>> print('jim','green ')
jim greem
The third type is also unique to python. Just put two strings together, with or without blanks in between: the two strings are automatically concatenated into one string:
>>> print('jim''green')
jimgreen
The fourth function is more powerful, drawing on the function of the printf function in C language. If you If you have a C language foundation, just read the documentation to find out. This method uses the symbol "%" to connect a string and a group of variables. The special marks in the string will be automatically replaced with the variables in the variable group on the right:
>>> print(' %s,%s'%('jim','green'))
jim,green
The fifth technique is to use the string function join. This function takes a list and then concatenates each element in the list with a string:
var_list = ['tom', 'david', 'john']
a = '
'
>>> print(a.join(var_list) )
david
john
In fact, there is another string connection method in python, but the Not much, just string multiplication, such as:
The above is the detailed content of Introduction to five methods of python string concatenation. For more information, please follow other related articles on the PHP Chinese website!