Home > Back-end >  How can I refactor this python script better?
How can I refactor this python script better?

Time:01-07

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

CodePudding user response:

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 ""

CodePudding user response:

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`

CodePudding user response:

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
  •  Tags:  
  • Related