首页 > 解决方案 > 在字符串中第二次出现特定字符后删除文本 - 有更好的方法吗?

问题描述

在此示例中,我想删除第二个逗号后的文本。string = "这是字符串,删除第二个逗号后的文本,将被删除。"

我想出了这个解决方案:

text = "This is string, remove text after second comma, to be removed."

k=  (text.find(",")) #find "," in a string
m = (text.find(",", k+1)) #Find second "," in a string
new_string = text[:m]

print(new_string)

它有效,但如何以更 Pythonic 的方式制作它?

标签: python-3.xstringslice

解决方案


我想这就是你要找的:

 text = "This is string, remove text after second comma, to be removed."
 print(''.join(text[:[pos for pos, char in enumerate(text) if char == ','][1]+1]))

推荐阅读