W
W
weranda2016-05-27 10:16:05
Python
weranda, 2016-05-27 10:16:05

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

It would seem that only single spaces should remain, but no - they remain even if two thousand replacements are used.
Please explain why this is happening.
PS
It is clear that regular expressions can be used, but the work of this particular method is of interest.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2016-05-27
@weranda

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]

you change every 3 spaces to 1
c=a.replace('   ', ' ', 2000)
>>> [len(x) for x in re.split('\d',c)]
[0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 0]

Accordingly, where the number of spaces is less than 3 - we leave them
Where more or equal - every three spaces we change by one + the remainder is not divisible by 3
For example, for 8 spaces:
>>> (lambda x: x//3 + x%3)(8)
4

For 9:
>>> (lambda x: x//3 + x%3)(9)
3

Parameter 2000 only indicates that no more than 2000 replacements should be made in each case. Since you obviously have fewer spaces in the example, this parameter has no effect. If there were more, then the number of replacements would be made, not more than 2000.
The change in the third parameter is visual:
>>> [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 question

Ask a Question

731 491 924 answers to any question