欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python split and join

程序员文章站 2024-03-26 11:42:17
...

split()方法默认以空格为分隔符,并把一系列字符串全部分开并返回一个列表。然而,我们也可以自己指定分隔符和分隔次数,如下面所示:

sentence = "enzymes and other proteins come in many shapes."
words = sentence.split() # 这个为默认设置,表示以空格为分隔符,分隔所有, 与 words=sentence.split (' ', -1)表示的结果一样,-1表示分隔所有
print(words)
words = sentence.split(' ', 1) # 这里设置了分隔次数为1,表示分隔为两部分
print(words)
words = sentence.split("and") # 这里指定了分隔符为“and”
print(words)

// 输出结果为:

['enzymes', 'and', 'other', 'proteins', 'come', 'in', 'many', 'shapes.']
['enzymes', 'and other proteins come in many shapes.']
['enzymes ', ' other proteins come in many shapes.']

join()方法,把一个序列中的所有元素,按照指定的连接符,合并成一个字符串并返回对象结果。

list = ['enzymes', 'and', 'other', 'proteins', 'come', 'in', 'many', 'shapes.']
words = '_'.join(list)
print(words)
words = ' '.join(list)
print(words)

// 输出结果为:
enzymes_and_other_proteins_come_in_many_shapes.
enzymes and other proteins come in many shapes.