mariano mariano - 5 months ago 11
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

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(',')]

result

['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', '')
    result.append(formatted_element)

In your case you should have done this:

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

or

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

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

http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/

and you can always refer to the docs

https://docs.python.org/3.5/tutorial/datastructures.html#list-comprehensions