gpt4 book ai didi

python - 将字符串合并在一起,直到出现一个符号

转载 作者:太空宇宙 更新时间:2023-11-03 13:54:49 25 4
gpt4 key购买 nike

将字符串合并到列表中,直到字符串中出现一个符号。

names = ['My name is john.', 'My', 'name', 'is Andrew.']

“我叫约翰。”是正确的

如何连接:"My name is Andrew."?知道列表可能不同。

symbols = ['.', ':']
for i in range(len(names)-1):
if names[i][-1] not in symbols:
print(names[i] + ' ' + names[i+1])

试过这个是有效的,但不是我想要的。

有没有人有什么想法或建议?

最佳答案

您可以利用print()end 可选参数。

names = ['My name is john.', 'My', 'name', 'is Andrew.']
symbols = ['.', ':']
for phrase in names:
print(phrase, end=" ")
if (phrase[-1] in symbols):
print()

输出:

My name is john. 
My name is Andrew.

如果你想将它们存储在一个列表中,你可以轻松地使用两个不同的列表:

names = ['My name is john.', 'My', 'name', 'is Andrew.']
symbols = ['.', ':']
phrases = []
current = []
for phrase in names:
current.append(phrase)
if (phrase[-1] in symbols):
phrases.append(" ".join(current))
current = []
print(phrases)

输出:

['My name is john.', 'My name is Andrew.']

我们可以使用单个列表:

names = ['My name is john.', 'My', 'name', 'is Andrew.']
symbols = ['.', ':']
phrases = [""]
for phrase in names:
phrases[-1] += phrase
if (phrase[-1] in symbols):
phrases.append("")
del phrases[-1] # Remove the last empty append
print(phrases)

输出:

['My name is john.', 'Mynameis Andrew.']

或者如果你喜欢Regular Expresions :

import re
names = ['My name is john.', 'My', 'name', 'is Andrew.']
print([phrase.strip() for phrase in re.split(r"[\.:]", " ".join(names))[:-1]])

输出:

['My name is john', 'My name is Andrew']

接受一些边缘情况:

results = [phrase.strip() for phrase in re.split(r"[\.:]", " ".join(names))[:-1]]
if (results[-1] == ""):
del results[-1]
print(results)

使用:

>>> ['My name is john.', 'My', 'name', 'is Andrew.', 'test test']
['My name is john', 'My name is Andrew', 'test test']

要保留 .:,您应该使用 @Jon clements评论:

import re
names = ['My name is john.', 'My', 'name', 'is Andrew.']
print([phrase.strip() for phrase in re.findall('(.*?[:.])', ' '.join(names))])

输出:

['My name is john.', 'My name is Andrew.']

接受一些边缘情况:

results = [phrase.strip() for phrase in re.findall('(.*?[:.])', ' '.join(names)) if phrase]
if (results[-1] in [".", ":"]):
del results[-1]
else:
results[-1] = results[-1][:-1]
print(results)

使用:

>>> ['My name is john.', 'My', 'name', 'is Andrew.', 'test test']
['My name is john.', 'My name is Andrew.', 'test test']

关于python - 将字符串合并在一起,直到出现一个符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58040053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com