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)

Python 编码为什么那么蛋疼?

  • 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-合并拼接字符串

猜你喜欢

转载自www.cnblogs.com/yexuesong/p/9232349.html