在 Python 中字符串链接有多种方式,这里简单作个总结,应该是比较全面的了,方便之后查阅。python
第一种,经过+
号的形式:数组
>>> a, b = 'hello', ' world' >>> a + b 'hello world'
第二种,经过,
逗号的形式:post
>>> a, b = 'hello', ' world' >>> print(a, b) hello world
可是,使用,
逗号形式要注意一点,就是只能用于print打印,赋值操做会生成元组:性能
>>> a, b ('hello', ' world')
第三种,直接链接中间有无空格都可:code
print('hello' ' world') print('hello''world')
%
第四种,使用%
操做符。orm
在 Python 2.6 之前,%
操做符是惟一一种格式化字符串的方法,它也能够用于链接字符串。字符串
print('%s %s' % ('hello', 'world'))
format
第五种,使用format
方法。get
format
方法是 Python 2.6 中出现的一种代替 %
操做符的字符串格式化方法,一样能够用来链接字符串。string
print('{}{}'.format('hello', ' world')
join
第六种,使用join
内置方法。it
字符串有一个内置方法join
,其参数是一个序列类型,例如数组或者元组等。
print('-'.join(['aa', 'bb', 'cc']))
f-string
第七种,使用f-string
方式。
Python 3.6 中引入了 Formatted String Literals(字面量格式化字符串),简称 f-string
,f-string
是 %
操做符和 format
方法的进化版,使用 f-string
链接字符串的方法和使用 %
操做符、format
方法相似。
>>> aa, bb = 'hello', 'world' >>> f'{aa} {bb}' 'hello world'
*
第八种,使用*
操做符。
>>> aa = 'hello ' >>> aa * 3 'hello hello hello '
推荐使用+
号操做符。
若是对性能有较高要求,而且python版本在3.6以上,推荐使用f-string
。例如,以下状况f-string
可读性比+
号要好不少:
a = f'姓名:{name} 年龄:{age} 性别:{gender}' b = '姓名:' + name + '年龄:' + age + '性别:' + gender
推荐使用 join
和 f-string
方式,选择时依然取决于你使用的 Python 版本以及对可读性的要求。