Six methods of Python string concatenation are introduced

  • 2020-06-19 10:40:24
  • OfStack

6 Methods of Python string concatenation:

1. The plus sign

First, those of you who have programming experience probably know that many languages use a plus sign to connect two strings, and Python USES a plus sign to connect two strings.


print 'Python' + 'Tab'

Results:


PythonTab

2. A comma

The second is a special case of concatenating two strings with a comma. If two strings are separated by a comma, the two strings will be concatenated, but with an extra space between them.


print 'Python','Tab'

Results:


Python Tab

3. Connect directly

The third is also unique to ython. As long as two strings are placed in the first string, with or without white space in the middle, the two strings will be automatically concatenated into one string.


print 'Python''Tab'

Results:


PythonTab

print 'Python'  'Tab'

Results:


PythonTab

4. The format

The fourth is more powerful and borrows from the printf functions in THE C language. If you have a basic knowledge of the C language, take a look at the documentation. This way, a string and a set of variables are concatenated with the symbol "%". The special mark in the string is automatically replaced with the variable in the right variable group:


print '%s %s'%('Python', 'Tab')

Results:


Python Tab

5 kinds of join

This is the trick, using the string function join. This function takes a list and concatenates each element of the list in turn with a string:


PythonTab
0

Results:


PythonTab
1

Sixth multi-line string concatenation ()


PythonTab
2

python automatically concatenates multiple lines into a single line when it encounters an unclosed parenthesis.It does not treat a newline or leading space as a character, as opposed to three quotes and a newline.

conclusion

That's all for Python string concatenation 6 methods, I hope it will be helpful to you. Those who are interested can continue to see other related topics on this site. If there is any deficiency, please let me know. Thank you for your support!


Related articles: