I was a given a string s = "1_2_3_4"
and I wanted to replace all "_"
with another char - "0"
.
I used s = ''.join([c for c in s if c != '_'])
to eliminate the "_"
from my string, but I don't know how to replace the values. I wanted to do something like s = ''.join([c for c in s if c != '_' else '0'])
but of course, that's invalid syntax.
I'm well aware that s.replace('_','0')
will be a much better option, but I'm just trying to understand how can I use if statements inside a list comprehension. This will serve me for other cases when the class I'm using will not have replace
method.