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"]
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.
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.
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:
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)]
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.
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']
[char.upper() if char != 'B' else char.lower() for char in "aBcDeF"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With