如果项目不以“。”结尾,则连接列表项目。

时间:2019-08-08 09:02:13

标签: python

我有一个字符串列表,如果它们的后缀不是以“。”结尾,我想将它们串联起来。

my_list=["This is my first string.","This is my second string, ","this is the middle of my second string","and this is the end of my second string."]
for index in range(len(my_list)):
    text=my_list[index]:
        if not text.endswith("."):

预期 ["This is my first string.","This is my second string, this is the middle of my second string and this is the end of my second string"]

1 个答案:

答案 0 :(得分:5)

这是将str.joinstr.split结合使用的一种方法。

例如:

my_list=["This is my first string.","This is my second string, ","this is the middle of my second string","and this is the end of my second string."]
result = [i.strip() + "." for i in " ".join(my_list).strip().split(".") if i]
print(result)

输出:

['This is my first string.',
 'This is my second string,  this is the middle of my second string and this is the end of my second string.']