首先从我们比较常见和常用的说起
方法一:+ 号拼接
这是一种最容易想到的的方法,不做多的解释,直接上代码如下:
str_1 = 'hello'
str_2 = 'world'
print(str_1 + ' ' + str_2) # hello world
方法二:% 号拼接
这种方式比较简洁,有许多 Python 程序员喜欢用,用法也比较简单,代码如下:
print("%s %s" % ("hello", "world")) # hello world
这种方式相比 + 号要更加灵活。它其实是一种格式化字符串的手段,提供很多种格式符来达到“美化”字符串格式的目的。具体格式化的更高级的用法不是本文的重点,所以这里不讲。
方法三:format 格式化 - python2.6
% 号的方式虽然比 + 号更灵活,但可读性相对还是差了点,同时还有一个缺点,如果 % 号的数量与后面参数的数量不一致,就会报错。这个时候 format 的好处就体现了。示例代码如下:
# 当使用位置作为参数标志时,和 % 的用法差不多
print("{0}: {1}".format("hello", "world"))
print("{}: {}".format("hello", "world"))
# 当需要传多个相同参数的时候,好处就体现出来了
param = "test"
print("{param} {param} {param}".format(param=param))
方法四:使用 str.join(iterable) 方法
字符串自带一个 join(iterable) 方法,该方法接受一个可迭代对象,该方法的用途是根据一个字符串连接可迭代对象中的字符串。当连接字符串为空时,就起到了无缝拼接的作用。需要注意的是,可迭代对象里的元素必须是字符串类型,否则会报错。示例代码如下:
# 可迭代对象的内容必须是一个字符串
print("".join(["hello", "world"])) # helloworld
print(",".join(["hello", "world"])) # hello,world
# 如果不是字符串将报错
print("".join((1, 2))) # TypeError: sequence item 0: expected string, int found
上面四种方法都是比较常见,也是我们用得比较多的方式。下面再介绍两种不是很常见,但比较高级一点的用法:
方法五:通过string.Template(template)对象拼接
Template 是 string 模块下的类,它接受一个 模板字符串。主要用于拼接的有两个方法:substitute(mapping, **kwds) 和 safe_substitute(mapping, **kwds),这两个方法均接受 mapping 对象,如 dict,**kwds 是关键字参数,即 k=v 形式的参数。
两个方法有一点小区别,即当 模板字符串中的参数与传入的参数不一致时,substitute() 方法会报错,而 safe_substitute() 方法不会。示例代码如下:
from string import Template
# 模板字符串,用 $+关键字 表示
s = Template('$who likes $what')
# 传入关键字参数
print(s.substitute(who='tim', what='kung pao')) # tim likes kung pao
d = {'who': 'tim', 'what': 'kung pao'}
# 传入 mappging 对象
print(s.substitute(d)) # tim likes kung pao
# 将字典当作关键字参数
print(s.substitute(**d)) # tim likes kung pao
d = {'who': 'tim'}
# 当 what 没有对应的值时,如果想不报错,应该使用 safe_substitute
# 它会将 $xxx 原样输出
print(s.safe_substitute(d)) # tim likes kung pao
print(s.substitute(d)) # KeyError: 'what'
方法六:使用 f-string - python3.6
这种方法在数据量大时,效率比较高,而且也更加灵活。示例代码如下:
# s = f'hello {name}' # 此时会报错,name未定义
name = 'demon'
print(f'hello {name}') # hello demon
print(f'hello {name.upper()}') # hello DEMON
介绍完比较高级的用法,最后再介绍两种比较巧的方式,一些语法上的规定,不是特别常用:
方法七:通过()拼接
直接上代码演示:
tuple_str = ('hello', 'world') # 用逗号隔开,是一个元组
fake_tuple_str = ('hello' ' ' 'world') # 用空格隔开
print(tuple_str) # ('hello', 'world')
print(fake_tuple_str) # hello world
方法八:print 多值输出
这种方法是直接输出拼接字符串,示例代码如下:
print('hello' 'world') # helloworld
print('hello', 'world', 'hhh') # hello world hhh
t = "hello"
m = 'world'
print(t, m) # hello world