Home >Backend Development >Python Tutorial >5 ways to concatenate strings in Python
Summarized the 5 methods of string connection in Python:
1. Plus sign
The first one, people with programming experience probably know that in many languages, the plus sign is used to connect two strings, and the same is true in Python. In this way, use "+" directly to connect two strings;
print 'Python' + 'Tab'
Result:
PythonTab
2. Comma
The second one is more special, use comma to connect two strings, if the two strings are separated by "comma" If open, then the two strings will be connected, but there will be one more space between the strings;
print 'Python','Tab'
Result:
Python Tab
3. Direct connection
The third one is also unique to Python, just put Put two strings together, with or without blanks in the middle, and the two strings will be automatically concatenated into one string;
print 'Python''Tab'
Result:
PythonTab
print 'Python' 'Tab'
Result:
PythonTab
4. Formatting
The fourth function It is relatively powerful and draws on the function of the printf function in C language. If you have a foundation in C language, just read 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:
print '%s %s'%('Python', 'Tab')
Result:
Python Tab
The fifth type of join
The trick is to use the string function join. This function accepts a list and then connects each element in the list with a string:
str_list = ['Python', 'Tab'] a = '' print a.join(str_list)
Result:
PythonTab