I have this table:
name | address | city | Result | Required Result |
---|---|---|---|---|
Sara | abc | NY | Sara, abc, NY | Sara, abc, NY |
def | CN | , def, CN | def, CN | |
Andrew | hij | Andrew, hij, | Andrew, hij | |
Mike | MD | Mike, , MD | Mike, MD |
I am getting the Result as in the "Result" filed as above table using the below Python code:
def calculateFullAddress(name, address, city):
if (name == " "):
return address ", " city
elif (address == " "):
return name ", " city
elif (city == " "):
return name ", " address
else:
return name ", " address ", " city
I need to get the results as in the "Required Result" field. Which logic should I use? Thanks
CodePudding user response:
Try this
return ', '.join([i.strip() for i in [name, address, city] if i.strip()])
instead of all that if else statements
This pretty much does the same, just using some in-built functions and methods in Python
def calculateFullAddress(name, address, city):
return ', '.join([i.strip() for i in [name, address, city] if i.strip()])
print(calculateFullAddress('Name', 'Address', 'City')) # with everything
print(calculateFullAddress(' ', 'Address', 'City')) # with no name
print(calculateFullAddress('Name', '', 'City')) # with no address
print(calculateFullAddress('Name', 'Address', ' ')) # with no city
Output
Name, Address, City
Address, City
Name, City
Name, Address
Tell me if its not working for you...
CodePudding user response:
Try the following method:
def calculateFullAddress(name, address, city):
res = ""
for value in [name, address, city]:
if value != "":
res = value ", "
return res.strip(", ")
CodePudding user response:
Yours didn't work because, it maynot be a string with a single space (" "
) in it, in case if its empty. The following code will work :-
def calculateFullAddress(name, address, city):
if not name.isalpha():
return f"{address}, {city}"
elif not address.isalpha():
return f"{name}, {city}"
elif not city.isalpha():
return f"{name}, {address}"
else:
return f"{name}, {address}, {city}"