Python Forum

Full Version: How's my list comprehension?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm just having fun, but can it be done better?
oob = lambda name: ''.join([letter if letter not in "aeiouAEIOU" else "oob" for letter in name])
oob("Name")
Outputs >>>"Noobmoob"
[Image: 50337809_1143130745880257_74678398887426...e=5CC6C909]
Maybe a translation table?

>>> mapping = str.maketrans({letter: "oob" for letter in "aeiou"})
>>> oob = "nilamo".translate(mapping)
>>> oob
'noobloobmoob'
Or a regular expression:
>>> import re
>>> re.sub("[aeiou]", "oob", "nilamo")
'noobloobmoob'
That's a bad use of lambda. You should only use lambda for single use functions passed as a parameter. Otherwise define a function. Here's a better use of lambda for this case:

oob = ''.join(map(lambda letter: 'oob' if letter.lower() in 'aeiou' else letter, 'Ichabod'))
(Jan-18-2019, 11:32 PM)ichabod801 Wrote: [ -> ]That's a bad use of lambda. You should only use lambda for single use functions passed as a parameter. Otherwise define a function. Here's a better use of lambda for this case:

oob = ''.join(map(lambda letter: 'oob' if letter.lower() in 'aeiou' else letter, 'Ichabod'))

Granted, but that's not what I asked about.
(Jan-18-2019, 10:41 PM)nilamo Wrote: [ -> ]Or a regular expression:
>>> import re
>>> re.sub("[aeiou]", "oob", "nilamo")
'noobloobmoob'

I like this one the best