Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

else if in list comprehension in Python3

I have a string with mixed cases, e.g. "aBcDeF". I want to upper-case all of the lower-case letters, and for the upper-case letters, only lower-case them if they're the letter 'B'. meaning, I want the result "AbCDEF". I've tried doing this in a list comprehension:

x = [str.upper(char) if char.islower() 
else str.lower(char) if char == "B" for char in "aBcDeF"]
  • The line breaks are just for reading convenience, in my code they are joined

However, I get the following syntax error:

Traceback (most recent call last):
  File "python", line 11
    else str.lower(char) if char == "B" for char in "aBcDeF"]
                                          ^
SyntaxError: invalid syntax

I've reviewed similar questions, but none provided me the answer.

like image 730
blz Avatar asked Oct 31 '16 19:10

blz


People also ask

How to perform list comprehension using if statement in Python?

In this example, we perform list comprehension using if statement (but without else) in Python. Here, we have taken a variable as num, the num = [i for i in range (10) if i>=5] is used for iteration. Then we have used for loop and assigned a range of 10, and then if condition is used as if >= 5.

What are if statements and for loops in Python?

Moreover, if statements and for loops are powerful ways to write clean, well-organized and logical code in Python. Python Lambda expression returns an expression’s value which it calculates using values of the arguments it gets. First, we create a list from a set in list comprehension syntax:

How to use elif in list comprehension in Python?

You can’t use elif in list comprehension because it’s not part of the if-else short-expression syntax in Python. Simple example code. [print ('Hi') if num == 2 and num % 2 == 0 else print ('Bye') if num % 2 == 0 else print ( 'buzz') if num == 5 else print (num) for num in range (1, 6)]

What is the advantage of if statement in Python?

It’s an easier way to create a list from a string or another list. It is faster than processing a list using the for loop. Moreover, if statements and for loops are powerful ways to write clean, well-organized and logical code in Python.


2 Answers

Sticking to your spirit of if-else list comprehension.

print([str.lower(char) if char.isupper() and char =='B' else str.upper(char) for char in "aBcDeF"])

prints:

['A', 'b', 'C', 'D', 'E', 'F']
like image 88
MooingRawr Avatar answered Sep 30 '22 16:09

MooingRawr


[char.upper() if char != 'B' else char.lower() for char in "aBcDeF"]
like image 37
Patrick Haugh Avatar answered Sep 30 '22 16:09

Patrick Haugh