python拼接字串的特殊方法,除了常見的+加號和%百分號以外,還可以不用加號直接拼>>> 'a''b' 結果:'ab',以及使用'abc{0}{1}{2}'.format(a, b, c)函式拼接
阿新 • • 發佈:2018-11-09
>>> 'a''b'
'ab'
>>> a, b, c = 1, 2, 3
>>> 'abc{0}{1}{2}'.format(a, b, c)
'abc123'
Python字串拼接詳解
Python字串拼接有以下5種常規方式
- 逗號
, - 加號
+ - 直接拼接
- 格式化拼接
- 字串函式join拼接
join
方法1/2 - 使用逗號或者加號進行拼接
- 逗號拼接會額外帶有一個空格。
#code
a = 'are'
b = 'you'
c = 'ok'
print(a, b, c)
print(a + b +c)
#output
are you ok
areyouok
- 逗號拼接數字會以字串的形式連線,而加號拼接數字就不再是拼接了,而是代表加法。
#code
a = 12
b = 4567
print(a, b)
print(a + b)
#output
12 4567
4579
- 加號無法拼接不同型別的變數,該問題同上,雖然
+
#code
a = 'abc'
b = 123
print(a, b)
print(a + b)
#output
abc 123
Traceback (most recent call last):
File "test2.py", line 7, in <module>
print(a + b)
TypeError: must be str, not int
- 使用加號拼接str和unicode會有UnicodeDecodeError。
該問題僅在python2中會遇到,因為python2當中的string編碼為ascii,若要使用Unicode,需要在字串前面加一個u。而到了python3中,所有的字串編碼都預設是Unicode了。
#code
a = '中文'
b = u'中文'
print a, b
print a + b
#output
中文 中文
Traceback (most recent call last):
File "test.py", line 7, in <module>
print a + b
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
-
Python3中的Unicode型別列印type轉變為了str型別,這就解釋了上面的那個問題。
-
python3
#code
num = 123
str1 = 'abc'
str2 = '中文'
str3 = u'中文'
print(type(num))
print(type(str1))
print(type(str2))
print(type(str3))
#output
<class 'int'>
<class 'str'>
<class 'str'>
<class 'str'>
- python2
#code
num = 123
str1 = 'abc'
str2 = '中文'
str3 = u'中文'
print type(num)
print type(str1)
print type(str2)
print type(str3)
#output
<type 'int'>
<type 'str'>
<type 'str'>
<type 'unicode'>
方法3 - 直接拼接
該方法只能用於字串的拼接,不能用於變數拼接
#code
print('abc''xyz')
#output
adcxyz
方法4 - 使用%或者format進行拼接
該方法借鑑於C語言的printf函式,多個變數是傾向於使用這種方法,因為它的可讀性更強。
#code
a = 'x'
b = 'y'
c = 'z'
print('abc%s' % a)
print('abc{0}{1}{2}'.format(a, b, c))
#output
abcx
abcxyz
方法5 - 使用字串函式join拼接
該方法多用於列表,元組,或者較大的字串拼接操作
#code
a = 'hello'
b = 'world'
str1 = [a, b]
print(''.join((a, b)))
print(''.join(str1))
#ouput
helloworld
helloworld
參考
Format strings vs concatenation
Is concatenating with “+” more efficient than separating with “,” when using print?
Difference between using commas, concatenation, and string formatters in Python
Py3-cookbook-合併拼接字串