我有一个要修改的字符串。因此,我使用.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']
答案 0 :(得分:1)
您可以使用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']