Skip to content
Advertisement

Clojure to Python: optional element in str like fn

Clojure version:

(defn greeting [& [name]]
  (cond-> "Hello" name (str " " name))

Naive Python version:

def greeting(name=None):
    if name is None:
        name = ''
    else: name = ' ' + name
    return 'Hello' + name

Question: How to make the python version shorter and more idiomatic?

Advertisement

Answer

def greeting(name=''):
    return f'Hello {name}'.strip() 

In case with None as default argument:

def greeting(name=None):
    return f'Hello {name}' if name else 'Hello'
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement