HassanK
HassanK

Reputation: 80

Changing all values of string to a certain value

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

Answers (5)

mgilson
mgilson

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

Daniel_Marcello
Daniel_Marcello

Reputation: 1

map(lambda x:"0"*len(x),["AB0","A","BBB"])

Upvotes: 0

Dan D.
Dan D.

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

TheClonerx
TheClonerx

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

Selcuk
Selcuk

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

Related Questions