3

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

2 Answers 2

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

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

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.