繁体   English   中英

python 删除字符串中第一个和第二个逗号之间的所有文本

[英]python remove all text between first and second comma in string

我有一个这样的字符串

gas,buck,12345,10fifty

我怎么能得到这个字符串?

gas,,12345,10fifty

一种选择可能是将列表推导与splitjoin一起使用,尽管它可能效率低下:

s = "gas,buck,12345,10fifty"

output = ",".join("" if i == 1 else x for i, x in enumerate(s.split(",")))
print(output) # gas,,12345,10fifty

或者,在这种特定情况下,您可以使用re

output = re.sub(',.*?,', ',,', s)
print(output) # gas,,12345,10fifty

你可以使用str. find str. find

>>> s = 'gas,buck,12345,10fifty'
>>> first_comma_idx = s.find(',')
>>> second_comma_idx = s.find(',', first_comma_idx)
>>> s = s[:first_comma_idx+1] + s[second_comma_idx:]
>>> s
'gas,,buck,12345,10fifty'

您可以将正则表达式与re.sub一起使用,最大替换为 1:

import re
s = 'gas,buck,12345,10fifty'
re.sub(',.*?,', ',,', s, count=1)

Output: 'gas,,12345,10fifty'

更好的例子
import re
s = 'a,b,c,d,e,f,g,h'
re.sub(',.*?,', ',,', s, count=1)
# 'a,,c,d,e,f,g,h'

您可以尝试像这样替换您的字符串:

your_string = "gas, buck, 12345, 10fifty"
your_string = your_string.replace(" buck", "")
print(your_string)

output:

gas,, 12345, 10fifty

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM