Python use in the same line "For", "If" and "Else"

Question:

I want to learn python "secrets", it’s possible to put all this code in one line?:

word_not_clean="Casà: 25$"
word_clean=""
for x in word_not_clean:
    if x in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789':
        word_clean+=x
    else:
        word_clean+='_'

This sentences work, but no replace especial characters:

word_clean="".join(x for x in word_not_clean if x in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')

But this sentence with else doesn’t works.

word_clean="".join(x for x in word_not_clean if x in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' else '_')

Thank you in advance.

Asked By: RBenet

||

Answers:

You can try like the below and also, you can use string.ascii_uppercase + string.ascii_lowercase + string.digits.

import string
word_not_clean="Casà: 25$"
chars_check = string.ascii_uppercase + string.ascii_lowercase + string.digits 


result = ''.join(x if x in chars_check else '_' for x in word_not_clean)

print(result)
# 'Cas___25_'

Explanation:

>>> import string
>>> string.ascii_uppercase + string.ascii_lowercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
Answered By: I'mahdi

If you want to do it using list comprehension (one-lining lines) add the if-else statement before the for:

chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
word_clean = "".join([x if x in chars else '_' for x in word_not_clean])
Answered By: Ernest Pokropek

There are two different kinds of if statements in generator expressions. The first kind (which I’ll call an “inclusion if”) comes after the for statement, and indicates whether a given item from an iterator should be included in the resultant list. This is what you’re using in the first example.

The second kind (which I’ll call a “ternary if”) comes before the if statement, and used Python’s ternary operator __ if __ else __ to decide what should be outputted by the iterator. This is what you want for the second example, but you need to reorder your terms:

OKAY = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”
word_clean = "".join(
    x if x in OKAY else '_'  # Ternary if
    for x in word_not_clean
)

Answered By: Adam Kern
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.