slek120
slek120

Reputation: 1155

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

Upvotes: 3

Views: 6821

Answers (2)

paxdiablo
paxdiablo

Reputation: 881453

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.

Upvotes: 5

Nafiul Islam
Nafiul Islam

Reputation: 82470

In[3]: "baab".replace('a', '', 1)
Out[3]: 'bab'

Will replace a only once with nothing, hence removing it.

Upvotes: 7

Related Questions