Else if in a list comprehension in Python3

I have a string with mixed cases, for example. "ABCDEF". I want all uppercase letters in uppercase, and for uppercase letters - only lowercase letters if they are the letter "B". I want to get the result "AbCDEF". I tried to do this in a list comprehension:

x = [str.upper(char) if char.islower() 
else str.lower(char) if char == "B" for char in "aBcDeF"]
  • Line breaks are for read only, in my code they connect

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 looked at similar questions, but no one gave me an answer.

+4
source share
5 answers

Adhering to the spirit of understanding if-else.

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']
+7
source
[char.upper() if char != 'B' else char.lower() for char in "aBcDeF"]
+3
source

@MooingRawr , if , - :

[x.upper() if x.islower() else x.lower() if x=='B' else x.upper() for x in "aBcDeF"]

() if:

[x.upper() if x.islower() else (x.lower() if x=='B' else x.upper()) for x in "aBcDeF"]

, x.upper().

:

new_str = ''

for x in "aBcDeF":
    if x.islower():
        new_str += x.upper()
    elif x == 'B';
        new_str += x.lower()
    else:
        new_str += x.upper()
+3

@Mooingrawr , , . , . , , , .

r = [str.lower(char)                  # Do this
     if char.isupper() and char =='B' # if this
     else str.upper(char)             # else this
     for char in "aBcDeF"]            # using these
print(r)
+1

@MooingRawr, , , else.

For example, it a = 3 if blahraises a SyntaxError but a = 3 if blah else 4does not.

0
source

Source: https://habr.com/ru/post/1659443/


All Articles