-4

I have a string like this

gas,buck,12345,10fifty

how can I end up with this string?

gas,,12345,10fifty
Lightsout
  • 3,454
  • 2
  • 36
  • 65
  • You need to clarify your intent. Do you want to know how to remove the second element of a comma-separated list? Remove all occurrences of "buck"? – sfjac Dec 21 '21 at 21:16

4 Answers4

3

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
j1-lee
  • 13,764
  • 3
  • 14
  • 26
1

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'
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
1

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'

better example
import re
s = 'a,b,c,d,e,f,g,h'
re.sub(',.*?,', ',,', s, count=1)
# 'a,,c,d,e,f,g,h'
mozway
  • 194,879
  • 13
  • 39
  • 75
0

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
Dekriel
  • 57
  • 1
  • 7
  • 3
    What if the string in the second element is unknown? Presumably the solution must be dynamic. – S3DEV Dec 21 '21 at 21:23
  • oh, ok. I guess you can use `re`, but I think they already have answers [here](https://stackoverflow.com/questions/23669024/how-to-strip-a-specific-word-from-a-string) – Dekriel Dec 21 '21 at 21:25