0

I am expected to ensure the code is written without unnecessary lines of code. Is there a way to refactor this and get the same output?

def format_name(first_name, last_name):
    if len(first_name) > 0 and len(last_name) > 0:
        return("Name: " + last_name + ", " + first_name)
    elif len(first_name) > 0 or len(last_name) > 0:
        return("Name: " + first_name + last_name)
    else:
        empty_string = ""
        return empty_string
    return string 


print(format_name("Ernest", "Hemingway"))
# Should return the string "Name: Hemingway, Ernest"

print(format_name("", "Madonna"))
# Should return the string "Name: Madonna"

print(format_name("Voltaire", ""))
# Should return the string "Name: Voltaire"

print(format_name("", ""))
# Should return an empty string
0

3 Answers 3

1

Without getting "too golfie", this should do the trick:

def format_name(first_name, last_name):
    name = f"{first_name}, {last_name}".strip(", ")
    return f"Name: {name}" if name else ""
Sign up to request clarification or add additional context in comments.

Comments

0

The refactored method tries to allocate the logic of the function in a single if condition.

def format_name(first_name, last_name):
    result = ''
    sep = ', ' if first_name and last_name else ' '
    
    if first_name or last_name:
        result = last_name + sep + first_name
        result = 'Name: ' + result.strip()
        
    return result
        
print(format_name("Ernest", "Hemingway")) # "Name: Hemingway, Ernest"
print(format_name("", "Madonna")) # "Name: Madonna"
print(format_name("Voltaire", "")) # "Name: Voltaire"
print(format_name("", "")) # `empty_string`

Comments

0

Use str.join and filter to build the name string:

def format_name(first_name, last_name):
    full_name = ", ".join(filter(None, (last_name, first_name)))
    if full_name:
        full_name = "Name: " + full_name
    return full_name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.