我想连接以“,”和“;”结尾的字符串并在字符串以“。”结尾时停止。
string2 = "Hello World;"
string3 = "Hello World,"
string4 = "Hello Word."
my_list = [string2, string3, string4]
def concat_strings(my_list):
N = len(my_list)
for idx in range(0, N):
text = my_list[idx]
if text[-1:] != '.':
text = text + my_list[idx + 1]
else:
print('False')
my_list[idx] = text
return my_list
my_list2 = concat_strings(my_list)
我想要的是“ Hello World; Hello World, Hello World.
”
我得到的是:
"Hello World;Hello World,"
"Hello World,Hello World."
"Hello World."
答案 0 :(得分:2)
我认为解决方案应涵盖不同的情况。有时,标点符号可能出现在字符串的开头,或者有时在字符串中不存在标点符号。也可能有任何随机标点符号。您指定的另一个条件是要在字符串中包含'。'。然后停止迭代其他字符串。
以下解决方案使用punctuation
库中可用的string
:
string2 = "Hello World;"
string3 = "Hello World,"
string4 = "Hello World."
string5 = "Hello World"
my_list = [string2, string3, string4, string5]
punctuation_list = list(punctuation)
stop = '.'
from string import punctuation
l = [string for string in my_list for i in string if any([i in punctuation_list])]
l1 = []
for i in l:
if i.endswith(stop):
l1.append(i)
break
else:
l1.append(i)
print(''.join(l1))
'Hello World;Hello World,Hello World.'
答案 1 :(得分:1)
使用list-comprehension
:
s = [string2, string3, string4]
print(" ".join([x + x if x.endswith(';') and x.endswith(',') else x for x in s]))
输出:
Hello World; Hello World, Hello Word.
编辑:
由于可以更改顺序,因此这是使用set()
的方法:
s = [string4, string3, string2] # change the sequence to however you may
p = [x for x in s if x.endswith(';') or x.endswith(',')]
print(" ".join(p + list(set(s) - set(p))))
答案 2 :(得分:1)
您应该保持简单:仅附加到输出,当字符串以'.'
结尾时停止附加
data = ["Hello World;", "Hello World.", "Hello World,"]
out = []
for s in data:
out.append(s)
if s.endswith('.'):
break
print(' '.join(out))
输出:
Hello World; Hello World.