# 分割字符串
strs='This is an example of cutting' #创建字符串
#以空格为分隔符将字符串全部分割
print(strs.split()) # ['This', 'is', 'an', 'example', 'of', 'cutting']
#以空格为分隔符将字符串分割3次
print(strs.split(' ',3)) # ['This', 'is', 'an', 'example of cutting']
3、连接字符串
join()方法用于将序列中的元素以指定的字符连接,生成一个新的字符串。
语法格式:
str.join(sequence)
其中,str表示连接符,可以为空,sequence表示要连接的序列
# 连接字符串
print('-'.join('Python!')) # P-y-t-h-o-n-!
#例:将字符串“Rain falls on field and tree”中的多余空格删除,即如果有连续空格只保留一个
strs='Rain falls on field and tree'
print('原文:',strs)
split_strs=strs.split() #以空格为分割符,将strs全部分割
print("以空格分割后:",split_strs) # ['Rain', 'falls', 'on', 'field', 'and', 'tree']
join_strs=' '.join(split_strs) # 用空格连续分割后的字串
print('只留一个空格的结果:',join_strs) # Rain falls on field and tree
#移除字符串的首尾字符
#例:使用strip()方法移除字符串‘110This is an test0001'中的‘0'和‘1'
strs='110This is an test0001'
#移除两端的1
print(strs.strip('1')) # 0This is an test000
# print(strs.strip('0')) # 结果:110This is an test0001 说明移除两端需要按顺序移除
#移除两端的1和0
print(strs.strip('10')) # This is an test
# 分割字符串
strs='This is an example of cutting' #创建字符串
#以空格为分隔符将字符串全部分割
print(strs.split()) # ['This', 'is', 'an', 'example', 'of', 'cutting']
#以空格为分隔符将字符串分割3次
print(strs.split(' ',3)) # ['This', 'is', 'an', 'example of cutting']
3、连接字符串
join()方法用于将序列中的元素以指定的字符连接,生成一个新的字符串。
语法格式:
str.join(sequence)
其中,str表示连接符,可以为空,sequence表示要连接的序列
# 连接字符串
print('-'.join('Python!')) # P-y-t-h-o-n-!
#例:将字符串“Rain falls on field and tree”中的多余空格删除,即如果有连续空格只保留一个
strs='Rain falls on field and tree'
print('原文:',strs)
split_strs=strs.split() #以空格为分割符,将strs全部分割
print("以空格分割后:",split_strs) # ['Rain', 'falls', 'on', 'field', 'and', 'tree']
join_strs=' '.join(split_strs) # 用空格连续分割后的字串
print('只留一个空格的结果:',join_strs) # Rain falls on field and tree
#移除字符串的首尾字符
#例:使用strip()方法移除字符串‘110This is an test0001'中的‘0'和‘1'
strs='110This is an test0001'
#移除两端的1
print(strs.strip('1')) # 0This is an test000
# print(strs.strip('0')) # 结果:110This is an test0001 说明移除两端需要按顺序移除
#移除两端的1和0
print(strs.strip('10')) # This is an test