Python:拆分字符串不丢失拆分字符

Python: Split string without losing split character

string = 'Hello.World.!'

我的尝试

string.split('.')

输出

['Hello', 'World', '!']

目标产出

['Hello', '.', 'World', '.', '!']

你可以这样做:

string = 'Hello.World.!'

result = []
for word in string.split('.'):
    result.append(word)
    result.append('.')

# delete the last '.'
result = result[:-1]

您也可以像这样删除列表的最后一个元素:

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]