-4

I have a string like this

gas,buck,12345,10fifty

how can I end up with this string?

gas,,12345,10fifty
bakalolo
  • 3,153
  • 2
  • 28
  • 54
  • 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
  • 10,540
  • 3
  • 12
  • 22
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
  • 15,168
  • 3
  • 22
  • 38
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
  • 81,317
  • 8
  • 19
  • 49
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
  • 59
  • 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