+ 2
why I can't understand str.replace() function ?
print("abc".replace("","|")) print("".replace("","abc",3)) #no output why? run the code I posed below and explain it to me I am really unable to understand it... so confusing... https://code.sololearn.com/cf5Trk3ULj8P/?ref=app
10 Antworten
+ 9
replace() function does not modify the string that should be changed in place, but returns a new string.
txt = "hello"
new = txt.replace("l","x") # all characters "l" will be replaced by character "x"
print(new) # result is: "hexxo"
# with python 3.8 you can do it a bit more simpler with the walrus operator
print(new := txt.replace("l","x")
The string / substring to replace and the replacement itself are not limited to single characters.
+ 4
mohammad hosein norouzi
Why do u post the same answer that Jayakrishna posted 1 day earlier..?
+ 3
Jayakrishna🇮🇳 the thing is that :
- "" in "" is True
- "".count("") == 1
- "".replace("", "abc") == "abc"
BUT
- "".replace("", "abc", n) == ""
His question is : why when you specify the last argument of replace (by default -1), it suddenly behaves differently?
+ 2
Replace function takes first argument as regex. So replace function consider a string abc as [ '', 'a', '', 'b', '','c', '' ] , here ''(single quotes) empty charecter. This is strange outcome by regex.. So every empty charecter is replaced by 'l'.
In 2nd statement the 3 is about maximum number of replacements to be taken place.. So range replacements are 0 to 3(inclusive).
+ 1
I agree, this is a weird behaviour...
And "".count("") returns 1.
It's very confusing, indeed.
+ 1
Alphin K Sajan Lothar i know str.replace() function
will you explain the lines that I posted above?
+ 1
Ratnapal Shende apparently, it is a normal behaviour of replace. This 'bug' will be resolved in Python3.9, so that :
- "".replace("", "abc")
And
- "".replace("", "abc", n)
Will give the same output.
So we have to wait for Python3.9 😉
0
2nd string is empty string. It don't have any empty charecters even so doesn't output anything.. Doesn't replace anything also....
0
Théophile OK bro Thank you so much!
please explain the first line of my code also
0
Replace function takes first argument as regex. So replace function consider a string abc as [ '', 'a', '', 'b', '','c', '' ] , here ''(single quotes) empty charecter. This is strange outcome by regex.. So every empty charecter is replaced by 'l'.
In 2nd statement the 3 is about maximum number of replacements to be taken place.. So range replacements are 0 to 3(inclusive).
Good luck.