1

Please explain what is going on with this:

'aaaaaaaaaaa'.replace('aaa','')

Output!:

'aa'

I expected only 3 'aaa' to be replaced in the original string. Please suggest an explanation or better approach.

3
  • 1
    "I expected only 3 'aaa' to be replaced in the original string." Okay? I see 11 as in total. If you replace aaa with nothing, three times, then shouldn't there be 2 left? Exactly what result did you expect instead, and why? "Please suggest an explanation or better approach." Better approach to what? What is the actual problem you are trying to solve? Please try to show a clearer example, with both actual and expected output, and also use full English sentences to describe the task. Commented Feb 26, 2022 at 23:53
  • 1
    Try: 'aaaaaaaaaaa'.replace('aaa','x'). How many x do you count? Commented Feb 26, 2022 at 23:54
  • Also: Did you try reading the documentation for str.replace? For example, by using help(str.replace) at the REPL, or by looking up documentation on docs.python.org? Commented Feb 26, 2022 at 23:54

3 Answers 3

1
'aaaaaaaaaaa'.replace('aaa','',1)

Apparently the function accepts the number of replacements as a third argument!

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

Comments

0

the official documentation of the "replace" method states

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.

If you want to replace only the first occurrence of "aaa" write.

'aaaaaaaaaaa'.replace('aaa', '', 1)

Comments

0

The .replace() function will replace every instance of your first parameter with your second parameter. Since your original String contained 11 characters, 3 sets of "aaa" were replaced by 3 sets of "", leaving only "aa" behind.

If you only want to replace one set of "aa" we can use a different approach using indexing and substrings:

Using the .index() function we can find the first instance of "aaa". Now, we can simply remove this section from our String:

index = x.index('aa')
x = x[0: index] + x[index + 2:]
print(x)

I hope this helped! Please let me know if you need any further details or clarification :)

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.