I have a string like this
gas,buck,12345,10fifty
how can I end up with this string?
gas,,12345,10fifty
I have a string like this
gas,buck,12345,10fifty
how can I end up with this string?
gas,,12345,10fifty
One option might be using list comprehension with split
and join
, although it might be inefficient:
s = "gas,buck,12345,10fifty"
output = ",".join("" if i == 1 else x for i, x in enumerate(s.split(",")))
print(output) # gas,,12345,10fifty
Alternatively, in this specific case, you can use re
:
output = re.sub(',.*?,', ',,', s, count=1)
print(output) # gas,,12345,10fifty
You could use 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'
You can use a regex with re.sub
and a maximum substitution of 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'
you can try to replace your string like this:
your_string = "gas,buck,12345,10fifty"
your_string = your_string.replace("buck", "")
print(your_string)
output:
gas,, 12345, 10fifty