python - 合并列表的索引内容
问题描述
我有一个要修改的字符串。因此我使用 .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']
解决方案
您可以使用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']
推荐阅读
- javascript - 在Angular中由Javascript动态创建的按钮上调用jQuery函数
- xpages - 如何在 xpages 上将字符集设置为 utf-8?
- javascript - 如何从另一个 iframe 更改 iframe 内容?
- php - PHP:将 UTF8 字符编码为 html 实体
- laravel - 如何在htaccess上重定向域中保存参数?
- angular - 行为主题(Rxjs)被自动调用
- python - 使用 Pandas 数据框的条件格式
- node.js - 在 Node Bull 中完成后删除作业不起作用
- python - 数组广播
- html - 浮动语句正在破坏块级元素?