Search code examples
pythonstringreplace

How do I remove a character once from a string [python]?


Is there a better way than what I am doing?

word = "baab"
word = word[:word.find('a')]+word[word.find('a')+1:]
print word #bab

Solution

  • You can use the string replace function with a maximum count:

    s = s.replace('a','',1)
    

    as in the following transcript:

    >>> s = "baab"
    >>> s = s.replace('a','',1)
    >>> s
    'bab'
    

    From the documentation:

    str.replace(old, new[, count])

    Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.