Summary of python string concatenation

  • 2020-04-02 13:58:36
  • OfStack

There are many ways to concatenate strings in python, so here's a summary:

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

Here is a specific analysis:

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.join(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 * 3 = 'abcabcabc'

Hopefully, the examples described in this article will be helpful in your Python programming.


Related articles: