分享

Python 3.6 学习系列之字符串的合并

 庆亮trj21bcn0z 2017-12-12

字符串的合并

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

TypeError: cannot concatenate 'str' and 'int' objects

下面的代码演示了字符串的连接方法:

Python 3.6 学习系列之字符串的合并

# 使用 + 链接字符串

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 3.6 学习系列之字符串的合并

可见,使用“+”对多个字符串进行连接稍显烦琐。Python提供了函数join()连接字符串,join()配合列表实现多个字符串的连接十分方便。

代码实例如下:

Python 3.6 学习系列之字符串的合并

# 使用join()连接字符串

print('==========# 使用join()连接字符串==========')

strs = ['hello', 'world', 'hello', 'china']

result = ''.join(strs)

print(result)

【代码说明】

第15行代码用列表取代变量,把多个字符串存放在列表中。

第16行代码调用join(),每次连接列表中的一个元素。

【运行结果】

Python 3.6 学习系列之字符串的合并

reduce()的作用就是对某个变量进行累计。这里可以对字符串进行累计连接,从而实现多个字符串进行连接的功能。

代码实现如下:

Python 3.6 学习系列之字符串的合并

# 使用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中的一个元素。

【运行结果】

Python 3.6 学习系列之字符串的合并

ALL:

Python 3.6 学习系列之字符串的合并

Python 3.6 学习系列之字符串的合并

# 使用 + 链接字符串

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('========================================')

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多