Summary of N ways to concatenate python strings

  • 2020-04-02 14:03:51
  • OfStack

There are many ways to concatenate strings in python. I'm writing code today.

Original string concatenation: str1 + str2
Python's new string concatenation syntax: str1, str2
Strange way to string: str1, str2
% connection string: 'name:%s; Sex: '% (' Tom ', 'male')
String list join: STR. Join (some_list)

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

'Jim' + 'Green' = 'JimGreen'

The second is special. If two strings are separated by a comma, the two strings are concatenated, but there is an extra space between them:

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

The third is also unique to python, as long as you put two strings together with or without white space: two strings are automatically concatenated into one string:

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

The fourth kind of function is more powerful, borrowing the function of printf function in C language, if you have the foundation of C language, look at the document to know. In this way, the symbol "%" is used to connect a string with a set of variables. The special mark in the string is automatically replaced with the variable in the right variable group:

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

The fifth is a trick, using 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. oin (var_list) = 'tom# # # # # david# John'

In fact, there is also a string concatenation method in python, but it is not used much, which is string multiplication, such as:

A = 'ABC'
A times 3 is 'abcabcabc'.


Related articles: