mariano mariano - 1 year ago 58
Python Question

How do I replace all zeroes in a python list with nothing?

I need to replace the zeros in newsplitted with nothing. Basically, I need to remove them. How do I do this WITHOUT imports? Can Anyone help?

input_string = "01-result.xls,2-result.xls,03-result.xls,05-result.xls"
# Must be turned into ['result1','result2', 'result3', 'result5']

splitted = input_string.split(',')

newsplitted = ["".join(x.split('.')[0].split('-')[::-1]) for x in splitted ]

This is what I tried so far:

final = []
for Y in newsplitted :
final =[Y.replace('0','')]

Just for the sake of learning, if I wanted to do the replace part at the end in another for loop, how would one do that????

Answer Source

A one liner with a list comprehension

input_string = "01-result.xls,2-result.xls,03-result.xls,05-result.xls"

result = [''.join(i.split('-')[::-1]).replace('.xls', '').replace('0', '') for i in input_string.split(',')]


['result1', 'result2', 'result3', 'result5']

This is essentially the same as

result = []
for i in input_string.split(','):
    formatted_element = ''.join(i.split('-')[::-1]).replace('.xls', '').replace('0', '')

In your case you should have done this:

[Y.replace('0', '') for Y in newsplitted]


final = []
for Y in newsplitted :

i'll suggest you read more about list comprehensions in python

and you can always refer to the docs