2

I was trying to figure out how to remove only a certain character from a string that appears more than once.

Example:

>>>x = 'a,b,c,d'
>>>x = x.someremovingfunction(',', 3)
>>>print(x)
'a,b,cd'

If anyone can help, that would be greatly appreciated!

Daniel Nicholson
  • 41
  • 1
  • 1
  • 7

3 Answers3

3

Split the original string by the character you want to remove. Then reassemble the parts in front of the offending character and behind it, and recombine the parts:

def remove_nth(text, separator, position):
    parts = text.split(separator)
    return separator.join(parts[:position]) + separator.join(parts[position:])

remove_nth(x,",",3)
# 'a,b,cd'
DYZ
  • 55,249
  • 10
  • 64
  • 93
1

Assuming that the argument 3 means the occurence of the character in question, you could just iterate over the string and count. When you find the occurence just create a new string without it.

def someremovingfunction(text, char, occurence):
    pos = 0
    for i in text:
        pos += 1
        if i == char:
            occurence -= 1
            if not occurence:
                return text[:pos-1] + text[pos:]
    return text

Usage example:

 print someremovingfunction('a,b,c,d', ',', 3)
nicecatch
  • 1,687
  • 2
  • 21
  • 38
bosnjak
  • 8,424
  • 2
  • 21
  • 47
-2

This may help

>>> x = 'a,b,c,d'
>>> ''.join(x.split(','))
'abcd'
Tabaene Haque
  • 576
  • 2
  • 10