Home  >  Article  >  Backend Development  >  Various methods of python string concatenation

Various methods of python string concatenation

高洛峰
高洛峰Original
2017-03-11 11:17:001434browse

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 can feel it.

There are many strings in python. Connection method, I am writing code today, let me summarize by the way:

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: ' % ('tom', 'male')
String list connection: str.join(some_list)

The first one, as anyone with programming experience probably knows, is to directly use "+" to connect two strings:

'Jim' + 'Green' = 'JimGreen'

The second type is special. If two strings are separated by "comma", then the two strings will be connected, but there will be an extra space between the strings:

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

The third method 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:

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

The fourth function is more powerful and is borrowed from C language The function of the printf function, if you have a C language foundation, you can know it by reading the documentation. 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:

'%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 = '
'

a.join(var_list) = 'tom

david

john'


In fact, there is another string connection method in python, but it is not used much, which is string multiplication, such as :

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

#########

The above is the detailed content of Various methods of python string concatenation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn