Why is 'ana' replaced with 'banana' only after the second call? Help please:
prop="ana anastasia ana ana re ana ana mere ana"
prop=" " prop " "
s = 'ana'
t = 'banana'
prop=prop.replace(" " s " "," " t " ")
print(prop) # banana anastasia banana ana re banana ana mere banana
prop=prop.replace(" " s " "," " t " ")
print(prop) # banana anastasia banana banana re banana banana mere banana
CodePudding user response:
In your first evaluation, _ana_ana_
is read as _ana_
ana_
(NB. spaces as underscore (_
) for clarity).
Only the first one meets the criterion to be replaced, the second one misses a space once the first _ana_
string is consumed.
You would need as many replacements as there are ana
words separated by a single space after each other.
One way around that is to use a regex with \b
as word delimiter:
prop="ana anastasia ana ana re ana ana mere ana"
import re
re.sub(rf'\b{s}\b', t, prop)
output: 'banana anastasia banana banana re banana banana mere banana'
CodePudding user response:
I'm representing space with _.
Here, when you replace "ana" with "banana" , whole "_ana_"
will be replaced. After replacing, even the space has been replaced, so the cursor will directly jump to "a" of next ana, so this will not be replaced. After second call, we have "_ana_"
so this time it will again replace it to banana and you'll get your desired result. Main point here is:
The cursor will jump directly to "a" of next ana after replacing
Instead, you can use split() function and check every word, if it is =="ana" then change it to "banana"
prop="ana anastasia ana ana re ana ana mere ana"
s1=""
for i in prop.split():
if i=="ana":
s1 ="banana" " "
else:
s1 =i " "
print(s1) # banana anastasia banana banana re banana banana mere banana