5 ways to concatenate strings in Python

高洛峰
Release: 2016-10-17 11:43:47
Original
1641 people have browsed it

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'
Copy after login

Result:

PythonTab
Copy after login
Copy after login
Copy after login
Copy after login

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'
Copy after login

Result:

Python Tab
Copy after login
Copy after login

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'
Copy after login

Result:

PythonTab
Copy after login
Copy after login
Copy after login
Copy after login
print 'Python'   'Tab'
Copy after login

Result:

PythonTab
Copy after login
Copy after login
Copy after login
Copy after login

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')
Copy after login

Result:

Python Tab
Copy after login
Copy after login

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)
Copy after login

Result:

PythonTab
Copy after login
Copy after login
Copy after login
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!