Home  >  Article  >  Backend Development  >  Introducing several common methods of string concatenation in python

Introducing several common methods of string concatenation in python

PHPz
PHPzOriginal
2017-04-02 14:01:091718browse

There are many

string connection methods in python. 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 method, as long as anyone with programming experience probably knows, directly use "+" to connect two String:

'Jim' + 'Green' = 'JimGreen'

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

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

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:

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

The fourth function is relatively powerful and draws on the functions of the printf function in C language. If you have a C language foundation, just read the documentation. In this way, the symbol "%" is used 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 method is a skill. Use the string function join. This function accepts a list, and then uses a string to connect each element in the list in turn:

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 Introducing several common methods of string concatenation in python. 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