Answer the question
In order to leave comments, you need to log in
Why doesn't the .replace() string method in python do the right amount of replacements?
Greetings
I do not understand why the string replacement method does not carry out the required number of replacements per string.
Example:
a = '0 1 2 3 4 5 6 7 8 9'
print(a.replace(' ', ' ', 2000))
>>> 0 1 2 3 4 5 6 7 8 9
Answer the question
In order to leave comments, you need to log in
Let's count the number of spaces between lines in your example:
>>> a = '0 1 2 3 4 5 6 7 8 9'
>>> import re
>>> [len(x) for x in re.split('\d',a)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
c=a.replace(' ', ' ', 2000)
>>> [len(x) for x in re.split('\d',c)]
[0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 0]
>>> (lambda x: x//3 + x%3)(8)
4
>>> (lambda x: x//3 + x%3)(9)
3
>>> [len(x) for x in re.split('\d',a.replace(' ', ' ', 0))]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> [len(x) for x in re.split('\d',a.replace(' ', ' ', 1))]
[0, 1, 2, 1, 4, 5, 6, 7, 8, 9, 0]
>>> [len(x) for x in re.split('\d',a.replace(' ', ' ', 2))]
[0, 1, 2, 1, 2, 5, 6, 7, 8, 9, 0]
>>> [len(x) for x in re.split('\d',a.replace(' ', ' ', 3))]
[0, 1, 2, 1, 2, 3, 6, 7, 8, 9, 0]
>>> [len(x) for x in re.split('\d',a.replace(' ', ' ', 4))]
[0, 1, 2, 1, 2, 3, 4, 7, 8, 9, 0]
>>> [len(x) for x in re.split('\d',a.replace(' ', ' ', 5))]
[0, 1, 2, 1, 2, 3, 2, 7, 8, 9, 0]
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question