CIsForCookies
CIsForCookies

Reputation: 12817

replacing chars in a string in one-liner

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.

Upvotes: 0

Views: 73

Answers (3)

Tom Wyllie
Tom Wyllie

Reputation: 2085

Try this generator expression with an in-line if else statement;

s = "1_2_3_4"
s = ''.join(((char if char != '_' else '0') for char in s))
print(s)

It's not a list comprehension, which is better in this use case. Still a one liner but is more efficient on larger strings.

Upvotes: 3

Ma0
Ma0

Reputation: 15204

Is this what you are looking for?

s = ''.join([c if c != '_' else '0' for c in s])

Btw another option would be:

s = '0'.join(s.split('_'))

I do not fully understand why not s.replace('_', '0') though.


Now as far as the "why" is concerned:

This is simply how the syntax of the language is. When the if comes before the for an else is also expected (an error is thrown if there isn't one). When the if comes after the for, an else following it is not allowed.

Upvotes: 4

omri_saadon
omri_saadon

Reputation: 10631

You can do this (it's better to use replace but you wished to use the join on a list):

s = "1_2_3_4"

s = ''.join([c if c != '_' else '0'  for c in s])

print (s)
>>> '1020304'

Upvotes: 2

Related Questions