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.
CodePudding user response:
'aaaaaaaaaaa'.replace('aaa','',1)
Apparently the function accepts the number of replacements as a third argument!
CodePudding user response:
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)
CodePudding user response:
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 :)