首页 > 解决方案 > 合并列表的索引内容

问题描述

我有一个要修改的字符串。因此我使用 .split() 函数,但有时我的源代码会在我需要删除的标点符号后自动添加一个空格。我知道如何隔离标点符号(在本例中为逗号),但不确定如何修改列表。这样做的最佳方法是什么?

    email_subject = "A B C D E F G H, I J"

    email_subject_contents_list = email_subject.split()

    for word in range(len(email_subject_contents_list)):

        print email_subject_contents_list[word]
        if email_subject_contents_list[word][-1] == ",":
            print("here it is at index %s" %(word))

    print email_subject_contents_list

目前:

A
B
C
D
E
F
G
H,
here it is at index 7
I
J
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H,', 'I', 'J']

理想情况下,我希望 email_subject_contents_list 打印为

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H,I', 'J']

标签: pythonlist

解决方案


您可以使用str.replace替换", "","然后使用str.split

前任:

email_subject = "A B C D E F G H, I J"
print( email_subject.replace(", ", ",").split() )

输出:

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H,I', 'J']

推荐阅读