Python 3.x 在字符串中第二次出现特定字符后删除文本-有更好的方法吗?
在这个例子中,我想删除第二个逗号后的文本。 string=“这是字符串,请删除第二个逗号后的文本,以便删除。” 我想出了这个解决方案:Python 3.x 在字符串中第二次出现特定字符后删除文本-有更好的方法吗?,python-3.x,string,slice,Python 3.x,String,Slice,在这个例子中,我想删除第二个逗号后的文本。 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))
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)
它是有效的,但如何使它更具Python风格?我想这就是你想要的:
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]))
一种可能是“,”.join(s.split(“,”)[:2]),使用s=“这是字符串,删除第二个逗号后的文本,将被删除。”。