Python string connection method summary, python string Summary
There are many string Connection Methods in python. Today we will summarize them here:
①. The original string connection method: str1 + str2
②. New python string connection Syntax: str1, str2
③. Strange string method: str1 str2
④. % Connection string: 'name: % s; sex: '% ('Tom', 'male ')
⑤ String list join: str. join (some_list)
The following is a detailed analysis:
First, as long as you have programming experience, we all know that you can directly use "+" to connect two strings:
'Jim' + 'Green' = 'JimGreen'
The second type is special. If the two strings are separated by commas, the two strings will be connected. However, there will be an extra space between the strings:
'Jim', 'Green' = 'Jim Green'
The third type is exclusive to python. As long as the two strings are put together, there is blank or no blank in the middle: The two strings are automatically connected to one string:
'Jim''Green' = 'JimGreen''Jim' 'Green' = 'JimGreen'
The fourth feature is quite powerful. I have used the printf function in C language for reference. If you have the C language basics, read the documentation. In this way, use the symbol "%" to connect a string and a group of variables. The special mark in the string will be automatically replaced with the variable in the variable group on the Right:
'%s, %s' % ('Jim', 'Green') = 'Jim, Green'
The fifth type is a skill. Use the string function join. This function accepts a list and uses strings to connect each element in the list in sequence:
var_list = ['tom', 'david', 'john']a = '###'a.join(var_list) = 'tom###david###john'
In fact, there is also a string connection method in python, but not many are used, that is, string multiplication, such:
a = 'abc'a * 3 = 'abcabcabc'
I hope the examples described in this article will help you with Python program design.
Python string connection
1. Not recommended
A = ['A', 'B', 'C', 'D']
Content =''
For I in:
Content = content + I
2.
A = ['A', 'B', 'C', 'D']
Content =''
Content = ''. join ()
3.
A = ['A', 'B', 'C', 'D']
Content =''
Content = '% s % s' % tuple ()
Print content
How can a python string be connected to an integer?
A = "abc"
B = 1
S = "% s % d" % (a, B)
Print s
Similar to c printf, convert any common types into strings