Reputation: 80
input = ["AB0","A","BBBB"]
output = ["000","0","0000"]
Is there a function like .replace("", "")
which could take in any input and give a string of zeros with the same number of characters?
Upvotes: 1
Views: 65
Reputation: 309949
Another way to do this (mostly for fun):
>>> input = ["AB0", "A", "BBBB"]
>>> zeros = ''.zfill
>>> [zeros(len(s)) for s in input]
['000', '0', '0000']
Note that this only works for filling with 0
. If you want to fill with different characters then this method won't work.
You could use ljsut
or rjust
to fill with different characters...
>>> input = ["AB0", "A", "BBBB"]
>>> pad = ''.ljust
>>> [pad(len(s), '1') for s in input]
['111', '1', '1111']
However, most of these are really just clever ways to do it. They aren't faster:
>>> timeit.timeit("[pad(len(s), '1') for s in input]", 'from __main__ import pad, input')
1.3355789184570312
>>> timeit.timeit("['1' * len(s) for s in input]", 'from __main__ import pad, input')
0.8812301158905029
>>> zeros = ''.zfill
>>> timeit.timeit("[zeros(len(s)) for s in input]", 'from __main__ import zeros, input')
1.110482931137085
though, depending on your particular preferences/background, you might find one way clearer to understand than another (and that's worth something)...
FWIW, my first instinct is to use the multiplication method as proposed in Selcuk's answer so that's probably what I find most easy to read and understandable...
Upvotes: 3
Reputation: 8577
You can use python 're' module, like following:
import re
input = ["AB0","A","BBBB"]
output = []
for value in input:
str = re.sub(".","0",value)
output.append(str)
print output
Upvotes: 0
Reputation: 343
This will work:
input = ["AB0","A","BBBB"]
output = ["0"*len(x) for x in input]
or the same:
input = ["AB0","A","BBBB"]
output = []
for x in input:
output.append("0"*len(x))
Upvotes: 2
Reputation: 59228
There is no such built-in function, but you can easily write a list comprehension for that:
>>> input = ["AB0","A","BBBB"]
>>>
>>> ["0" * len(item) for item in input]
['000', '0', '0000']
Upvotes: 3