字符串的合并
与Java语言一样,Python使用“+”连接不同的字符串。Python会根据“+”两侧变量的类型,决定执行连接操作或加法运算。如果“+”两侧都是字符串类型,则进行连接操作;如果“+”两侧都是数字类型,则进行加法运算;如果“+”两侧是不同的类型,将抛出异常。TypeError: cannot concatenate 'str' and 'int' objects

下面的代码演示了字符串的连接方法:
# 使用 + 链接字符串
print('========# 使用 + 链接字符串==============')
str1 = 'hello'
str2 = 'world'
str3 = 'hello'
str4 = 'china'
result = str1 + str2 + str3
print(result)
result += str4
print(result)
print('========================================')
【代码说明】
第7行代码,把变量str1、str2、str3的值连接起来,并把结果存放在变量result中。
第9行代码,使用运算符“+=”连接变量result和str4。
【运行结果】
可见,使用“+”对多个字符串进行连接稍显烦琐。Python提供了函数join()连接字符串,join()配合列表实现多个字符串的连接十分方便。
代码实例如下:
# 使用join()连接字符串
print('==========# 使用join()连接字符串==========')
strs = ['hello', 'world', 'hello', 'china']
result = ''.join(strs)
print(result)
【代码说明】
第15行代码用列表取代变量,把多个字符串存放在列表中。
第16行代码调用join(),每次连接列表中的一个元素。
【运行结果】
reduce()的作用就是对某个变量进行累计。这里可以对字符串进行累计连接,从而实现多个字符串进行连接的功能。
代码实现如下:
# 使用reduce()连接字符串
print('=========# 使用reduce()连接字符串=========')
from functools import reduce
import operator
strs = ['hello', 'world', 'hello', 'china']
result = reduce(operator.add, strs, '')
print(result)
print('========================================')
【代码说明】
第23行代码导入模块operator,利用方法add()实现累计连接。
第25行代码调用reduce()实现对空字符串“”的累计连接,每次连接列表strs中的一个元素。
【运行结果】
ALL:
# 使用 + 链接字符串
print('========# 使用 + 链接字符串==============')
str1 = 'hello'
str2 = 'world'
str3 = 'hello'
str4 = 'china'
result = str1 + str2 + str3
print(result)
result += str4
print(result)
print('========================================')
# 使用join()连接字符串
print('==========# 使用join()连接字符串==========')
strs = ['hello', 'world', 'hello', 'china']
result = ''.join(strs)
print(result)
print('========================================')
# 使用reduce()连接字符串
print('=========# 使用reduce()连接字符串=========')
from functools import reduce
import operator
strs = ['hello', 'world', 'hello', 'china']
result = reduce(operator.add, strs, '')
print(result)
print('========================================')