6 methods of Python string concatenation

6 methods of Python string concatenation

1. the plus sign

The first kind, people who have programming experience, probably know that many languages ​​use plus signs to connect two strings, and Python also uses "+" to connect two strings directly;

print 'Python' + 'Tab'

result:

PythonTab

2. Comma

The second one is special. Use a comma to connect two strings. If the two strings are separated by a "comma", the two strings will be concatenated, but there will be an extra space between the strings;

print 'Python','Tab'

result:

Python Tab

3. Direct connection

The third is also unique to Python. As long as two strings are put together with or without spaces in between, the two strings will be automatically concatenated into one string;

Example 1:

print 'Python''Tab'

result:

PythonTab

 

Example 2:

print 'Python'   'Tab'

result:

PythonTab

4. Format

The fourth function is more powerful, drawing on the function of the printf function in the C language. If you have a basic C language, look at the documentation to know.

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:

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

result:

Python Tab

5. join

Use the string function join; this function receives a list, and then connects each element in the list in sequence with a string:

str_list = ['Python', 'Tab']
a = ''
print a.join(str_list)

 result:

PythonTab

6. Multi-line string stitching ()

s = ('select *'
     'from atable'
     'where id=888')
print s, type(s)

#输出
select *from atablewhere id=888 <type 'str'>

Python encounters unclosed parentheses and automatically splices multiple lines into one line. Compared to the three quotation marks and line breaks, this method does not treat line breaks and leading spaces as characters.

Published 210 original articles · praised 37 · 170,000 views +

Guess you like

Origin blog.csdn.net/u012757419/article/details/103802210