string = 'Hello.World.!'
我的尝试
string.split('.')
输出
<块引用>['你好', '世界', '!']
目标输出
<块引用>['你好', '.', '世界', '.', '!']
答案 0 :(得分:2)
你可以这样做:
string = 'Hello.World.!'
result = []
for word in string.split('.'):
result.append(word)
result.append('.')
# delete the last '.'
result = result[:-1]
您也可以像这样删除列表的最后一个元素:
result.pop()
答案 1 :(得分:2)
使用 re.split 并在分隔符周围放置一个捕获组:
import re
string = 'Hello.World.!'
re.split(r'(\.)', string)
# ['Hello', '.', 'World', '.', '!']
答案 2 :(得分:2)
使用 re.split()
,第一个 arg 作为分隔符。
import re
print(re.split("(\.)", "hello.world.!"))
反斜杠用于转义“.”因为它是正则表达式中的特殊字符,而且括号也可以捕获分隔符。
相关问题:In Python, how do I split a string and keep the separators?
答案 3 :(得分:0)
如果您想在一行中执行此操作:
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]