Reversing first and last name - code not printing - python

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()

You should check for len(name.split()) in your conditionals as now you're checking the string length and not the word count.

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

You are using len on string which does return its' number of characters, consider that
print(len("Herbert von Knass"))
gives output
17

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()

Adding to the other answers re your conditionals, and using a .split(), suggesting the following code in your function to simplify your conditions:
def reverse_name(name):
name_parts = name.split(" ")
first = name_parts[0]
last = " ".join(name_parts[1:])
print(f"{last}, {first}") if last else print(first)
If a single name is entered, there will not be a last name (last is falsy), so only the first name (first) is printed.

Related

How to convert alphabetical input to numbers and add them together

i'm trying to convert user input into only alphabets, and convert each alphabet into a number(ex. a=1, b=2), then the numbers together. I've been able to complete the first part, but not sure how to do the second part.
import re
name = input("Name: ")
cleaned_name = filter(str.isalpha, name)
cleaned_name = "".join(cleaned_name)
print("Your 'cleaned up' name is: ", cleaned_name)
numbers = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,
'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
for al in range(len(cleaned_name)):
print(numbers,sep='+')
#if input is jay1joe2, cleaned name will be jayjoe
#after the 'numerology', will print the following below
#10+1+25+10+15+5 = 66
Something like this should work for what you're trying to do.
Note: I'm hardcoding the name here rather than using the user input, so it's easier to test it out if needed.
import string
# name = input("Name: ")
name = 'jay1joe2'
cleaned_name = filter(str.isalpha, name)
cleaned_name = "".join(cleaned_name)
print("Your 'cleaned up' name is: ", cleaned_name)
numbers = {char: i for i, char in enumerate(string.ascii_lowercase, start=1)}
result = list(map(numbers.get, cleaned_name))
print(*result, sep='+', end=' ')
print('=', sum(result))
Where the second part (after numbers) could also be written alternatively as follows, using f-strings in 3.6+:
result = [numbers[c] for c in cleaned_name]
print(f"{'+'.join(map(str, result))} = {sum(result)}")
Result:
Your 'cleaned up' name is: jayjoe
10+1+25+10+15+5 = 66
name = input("Name: ")
name = name.lower()
name1 = list(name)
Addition: int = 0
for k in name1:
if ord(k)-96 < 1 or ord(k)-96 > 26:
pass
else:
Addition = Addition + ord(k) - 96
print(Addition)
We can use ascii codes for Numbers and Characters :)

How can I make it where it will print the longest name/string that was inputed by the user

def myNames():
names = []
while True:
a = input("Enter Name: ")
if a != "done":
names.append(a)
elif a == "done":
return names
def all_lengths(myNames):
num_of_strings = len(myNames)
total_size = 0
for item in myNames:
total_size += len(item)
ave_size = float(total_size) / float(num_of_strings)
print(ave_size)
all_lengths(myNames())
def longestWord(myNames):
count = 0
for i in myNames:
if len(i) > count:
count = len(i)
word = I
print ("the longest string is ", word)
how can I make it print the longest name that was inputted by the user for example: out of Samantha and John it would say that Samantha was the longest name
longestName = ""
for name in myNames:
if len(name) > len(longestName):
longestName = name
print("The longest name is", longestName)
This will check the length of each username, and if the name of that username is longer than the current longest username, it will replace it.
You already have the function for it.
Just need to call the function longestWord().
Write longestWord(myNames()) at the end of the program. Right after,
def longestWord(myNames):
count = 0
for i in myNames:
if len(i) > count:
count = len(i)
word = i # Need to type I in lower case
print ("the longest string is ", word)
Update: Since, you don't want the function to ask for names again, you can move the function calling longestWord()inside the above function where it calculates average, with the parameter as myNames i.e.
def myNames():
names = []
while True:
a = input("Enter Name: ")
if a != "done":
names.append(a)
elif a == "done":
return names
def longestWord(myNames):
count = 0
for i in myNames:
if len(i) > count:
count = len(i)
word = i
print ("the longest string is ", word)
def all_lengths(myNames):
num_of_strings = len(myNames)
total_size = 0
for item in myNames:
total_size += len(item)
ave_size = float(total_size) / float(num_of_strings)
print(ave_size)
longestWord(myNames) # Calling the function with already given names
all_lengths(myNames())

In Python how do I make a space between a list and string?

I need to put a space between the list (a cat's name) and the index.
Right now it comes out like this:
Pussy0
Pinky1
Fats2
I want it to print out like this:
Pussy 0
Pinky 1
Fats 2
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
#print(name)
for i in range(len(catNames)):
print(catNames[i] + str(i))
Just do this:
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
#print(name)
for i in range(len(catNames)):
print(catNames[i] + " " + str(i))
Though its always better to use f-strings or format:
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
#print(name)
for i in range(len(catNames)):
print(f"{catNames[i]} {str(i)}")
Using f-strings makes the code much cleaner, and simpler to understand. Look here for more details. Note that f-strings are only for python 3.6 or above. If you have a version of python below 3.6, check my previous answer to see how you can use f-strings in below python 3.6.
Try string formatting:
catnames = ['Fuzzy', 'Pinky', 'Fats']
for i, cname in enumerate(catnames):
print('{} {}'.format(cname, str(i)))
I would suggest using string interpolation for this:
for i in range(len(catNames)):
print(f"{catNames[i]} {i}")
I with the help of "Demolution Brother" showed me how to write a list in a string followed by an index.
print(str(i),":",catNames[I])
print function
Turn the interfere into a string - (str(
After the str( we now have the interfere (str(I)
Important to use the , to separate the string to put in " : ". It has to be done with
double-quotes.
Now after the comma , we can continue with catNames[I]) (The List)
List item now prints after the index.
Answer - print(catNames[i], " : ", str(I))
Some of the other ways to it was tried out:
#print(str(i),":",catNames[i])
#print(catNames[i], i, end=' ')
#print(catNames[i],end=' ' + str(i))
The code -cat_names
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
#print(name)
for i in range(len(catNames)):
print(str(i),":",catNames[i])
#print(catNames[i], " : ", str(i))

Removing extra whitespace between words using for loop Python

I need to remove all excess white space and leave one space, between my words while only using if and while statements. and then state the amount of characters that have been removed and the new sentence
edit, it must also work for punctuation included within the sentence.
This is what I have come up with however it leaves me with only the first letter of the sentence i choose as both the number, and the final sentence. can anyone Help.
def cleanupstring(S):
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
else:
lasti = i
result += i
return result
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
Your code should be something like this:
def cleanupstring(S):
counter = 0
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
counter += 1
else:
lasti = i
result += i
return result, counter
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
The counter keeps track of how often you remove a character and your [0] and [1] work now the way you want them to.
This is because outputList is now a tuple, the first value at index 0 is now the result and the second value at index 1 is the counter.

Logic Error (Pythons): Not getting write output but function works?

Inputted:
Akash Das
Expected return:
Das Akash
My code is outputting:
Da Akash
Here's my code:
#a
def firstWord(string):
space = string.find(" ")
first = string[:space]
return first
#b
def removeFirst(string):
space = string.find(" ")
word = string[space + 1:]
return word
print(removeFirst("Akash Das"))
#c
def reversePhrase(string):
reverse = []
numSpace = string.count(" ")
reverse.append(firstWord(string))
while numSpace > 0:
string = removeFirst(string)
reverse.insert(0, firstWord(string))
numSpace -= 1
return reverse
def printReverse(string):
for i in reversePhrase(string):
print (i, end = " ")
#d
def main():
string = input("Enter a phrase. ")
print("Your reversed phrase is", end = " ") #call reverse
printReverse(string)
main()
And here's the output:
>>>
Das
Enter a phrase. Akash Das
Your reversed phrase is Da Akash
>>>
CSZ is right, that is simpler. But your problem is in firstWord. If the string has no spaces, then find will return -1. So space will be -1, and string[:space] will be string[:-1] which is all characters except the last. You just need to check whether you actually found a space:
def firstWord(string):
space = string.find(" ")
first = string[:space] if space >= 0 else string
return first
There is simplier way:
def main():
string = input("Enter a phrase. ")
print("Your reversed phrase is", end = " ")
print(' '.join(reversed(string.split())))
main()
output
Enter a phrase. Akash Das
Your reversed phrase is Das Akash
You are not taking care of the case when find returns -1, it happens when it does not find " ".
Try:
#a
def firstWord(string):
space = string.find(" ")
if space >=0:
first = string[:space]
else:
first = string
return first
Try this :
>>> import re
>>> name = 'Harsha Biyani'
>>> s = re.split('\W',s)
>>> s.reverse()
>>> ' '.join(s)
'Biyani Harsha'

Categories