I'm trying to reverse names given by the user, for example Herbert von Knass should be written as von Knass, Herbert. I've run into a brick wall now as my code doesn't print anything despite the print command, where am I going wrong? This is my code:
def reverse_name(name):
if len(name) == 2:
first = name.split()[0]
last = name.split()[-1]
print(f"{last}, {first}")
if len(name) == 3:
first = name.split()[0]
last = name.split()[-2] " " name.split()[-1]
print(f"{last}, {first}")
if len(name) == 1:
print(f"{name}")
def main():
name = input()
reverse_name(name)
if __name__ == "__main__":
main()
CodePudding user response:
You should check for len(name.split())
in your conditionals as now you're checking the string length and not the word count.
CodePudding user response:
Just change the usage of len(). Some basic change could look like this:
def reverse_name(name):
name_parts = name.split(" ")
reverse_name = name
if len(name_parts) == 2:
first = name_parts[0]
last = name_parts[1]
reverse_name = f"{last}, {first}"
elif len(name_parts) > 2:
first = name.split()[0]
last = name.split()[-2] " " name.split()[-1]
reverse_name = f"{last}, {first}"
print(reverse_name)
return reverse_name
CodePudding user response:
You are using len
on string which does return its' number of characters, consider that
print(len("Herbert von Knass"))
gives output
17
CodePudding user response:
None of the print()
statements are being triggered if the character length of the name is not 1, 2, or 3.
CodePudding user response:
You are using len() for finding len of full string, I think first you split then find len() like below then it works .
def reverse_name(name):
l=name.split(" ")
name_len=len(l)
if len(name) == 2:
first = name.split()[0]
last = name.split()[-1]
print(f"{last}, {first}")
if len(name) == 3:
first = name.split()[0]
last = name.split()[-2] " " name.split()[-1]
print(f"{last}, {first}")
if len(name) == 1:
print(f"{name}")
def main():
name = input()
reverse_name(name)
if __name__ == "__main__":
main()