【发布时间】:2021-07-06 00:23:14
【问题描述】:
string = 'Hello.World.!'
我的尝试
string.split('.')
输出
['你好','世界','!']
目标输出
['Hello', '.', 'World', '.', '!']
【问题讨论】:
标签: python arrays string split python-3.9
string = 'Hello.World.!'
我的尝试
string.split('.')
输出
['你好','世界','!']
目标输出
['Hello', '.', 'World', '.', '!']
【问题讨论】:
标签: python arrays string split python-3.9
你可以这样做:
string = 'Hello.World.!'
result = []
for word in string.split('.'):
result.append(word)
result.append('.')
# delete the last '.'
result = result[:-1]
你也可以像这样删除列表的最后一个元素:
result.pop()
【讨论】:
result.pop()来完成,而不是数组切片来创建一个新列表。
使用re.split 并在分隔符周围放置一个捕获组:
import re
string = 'Hello.World.!'
re.split(r'(\.)', string)
# ['Hello', '.', 'World', '.', '!']
【讨论】:
使用re.split(),第一个参数作为分隔符。
import re
print(re.split("(\.)", "hello.world.!"))
反斜杠是为了转义“.”因为它是正则表达式中的特殊字符,并且括号也用于捕获分隔符。
相关问题:In Python, how do I split a string and keep the separators?
【讨论】:
如果您想在一行中执行此操作:
string = "HELLO.WORLD.AGAIN."
pattern = "."
result = string.replace(pattern, f" {pattern} ").split(" ")
# if you want to omit the last element because of the punctuation at the end of the string uncomment this
# result = result[:-1]
【讨论】: