Name formatting in python with string splits - python-3.x

I have gotten mostly through this assignment but I am stuck as to obtain the proper outputs.
This assignment wishes that if the inputs are a full name, that the outputs are "last name, first initial. last initial. If the input was Stacy Estel Graham, the expected output should be Graham, S.E.
"Many documents use a specific format for a person's name. Write a program whose input is:
firstName middleName lastName
and whose output is:
lastName, firstInitial.middleInitial."
full_name = input()
mod_name = full_name.split(' ')
last_name= mod_name.pop(-1)
mod_name.join('.')
print(last_name)
print(mod_name)
I am completely lost on how to proceed.

You need to use '.'.join() to get the initials added.
To extract only the first char from the name, you can do mod_name[i][:1] where i is the index from 0 until last name - 1.
You can do something like this:
full_name = input('Enter your full name :')
mod_name = full_name.split(' ')
temp = '.'.join([mod_name[i][0] for i in range (0, len(mod_name) - 1)])
if temp == '':
print (mod_name[-1])
else:
print (mod_name[-1] + ', ' + temp + '.')
Here are some of the sample runs:
Enter your full name :Stacy Estel Sugar Graham
Graham, S.E.S.
Enter your full name :Stacy Estel Graham
Graham, S.E.
Enter your full name :Stacy Graham
Graham, S.
Enter your full name :Graham
Graham

Use:
def format_name(name):
names = name.split()
return f"{names[-1]}, {''.join([f'{i[0]}.' for i in names[:-1]])}"
Examples:
format_name('Stacy Estel Graham')
# > 'Graham, S.E.'
format_name('Randall McGrath')
# > 'McGrath, R.'

this code help you,but middle name is must for every person for creating your desire output
import re
s="Stacy Estel Graham"
words=s.split()
k=re.findall("[A-Z]",s)
p=words[-1]+","+k[0]+"."+k[1]
print(p)
Output:
Graham,S.E

Not with re :
full_name = input()
mod_name = full_name.split(' ')
last_name= mod_name.pop(-1)
first_inital = mod_name[0][0]
if len(mod_name) >= 2:
middle_inital = mod_name[1][0]
print(f'{last_name}, {first_inital}.{middle_inital}')
else:
print(f'{last_name}, {first_inital}.')
You can use string indexing and f' string format.
Input:
Hello World Python
Output:
Python, H.W.

full_name = input(')
mod_name = full_name.split(' ')
temp = '.'.join([mod_name[i][0] for i in range (0, len(mod_name) - 1)])
if temp == '':
print (mod_name[-1])
else:
print (mod_name[-1] + ', ' + temp + '.')

Related

My Five - stores five names and five numbers before being promoted for a number need input

For class I need to create a code that stores five names of your friends and five numbers in two separate arrays and then outputs the list of your five friends. The user would then be prompted for a number between 1 and 5, and the program will determine the person and the number to dial.
it should look something like -
1. Jack Black
2. Robert Downey Jr.
3. Chris Evens
4. Scarlett Johansson
5. Harry Potter
Please enter a number (1-5): *4*
Calling Scarlett Johansson at 416-568-8765
right now I have:
name = ["Paige"]
number = ["519-453-4839"]
#populate with a while loop
while True:
#add an element or q for quit
addname = input("Enter a name, or q to quit ").lower()
if addname == "q":
break
else:
theirnumber = input("Enter their number ")
#adds to the end of the list
name.append(addname)
number.append(theirnumber)
#when they break the loop
#print the lists side by side
print()
print("Name \t\t\t Number")
print("----------------------------------")
for x in range(len(name)):
print(f"{name[x]} \t\t\t {number[x]}")
#search for a gift and who gave it
searchItem = input("What name are you looking for? ")
if searchItem in name:
nameNumber = name.index(searchItem)
print(f"{name[nameNumber]} is the number {number[nameNumber]}")
else:
print("that is not a saved name, please enter a different name")
I'm not sure how to do it without asking for the numbers, if anyone has any ideas I would love to hear them.
#Mitzy33 - try to this and see if you follow, or have any other questions:
# two array for names, and the numbers
names = []
numbers = []
#populate with a while loop
while True:
# get the name and numbers:
name = input("Enter a name, or q to quit ")
if name == "q":
break
else:
number = input("Enter his/her number ")
#adds to the end of the list
names.append(name)
numbers.append(number)
#when they break the loop
#print the lists side by side
print(names)
print(numbers)
searchPerson = input("What name are you looking for? ").strip()
#print(searchPerson)
index = names.index(searchPerson)
print(f' {searchPerson} at {numbers[index]} ')
Output:
Enter a name, or q to quit John
Enter his/her number 9081234567
Enter a name, or q to quit Mary
Enter his/her number 2121234567
Enter a name, or q to quit Ben
Enter his/her number 8181234567
Enter a name, or q to quit Harry
Enter his/her number 2129891234
Enter a name, or q to quit q
['John', 'Mary', 'Ben', 'Harry']
['9081234567', '2121234567', '8181234567', '2129891234']
What name are you looking for? Harry
Harry at 2129891234
Instead of using two arrays you can do it using Python Dictionaries.
Use the name as the key and the number as the corresponding value.
peoples = {"Paige": "519-453-4839"}
You can add an item like that:
poeples["newName"] = "111-111-1111"
Then you can access the number like that:
peoples["Paige"]
So you can ask the name and return the number:
searchName = input("What name are you looking for? ")
print(f"{searchName} is the number {peoples[searchName]}")
If you have to use only arrays then you can find the index from the name:
searchName = input("What name are you looking for? ")
index = name.index(searchName)
print(f"{name[index]} is the number {number[index]}")

i want to delete the element even if user input is in small or Capital letter

nametoRemove = input("Enter the name you want to remove:")
print(nametoRemove)
name = ["Ramesh","Rakesh","Suresh"]
name.remove(nametoRemove)
print(name)
you can do it fith basic for loop and if statement:
nametoRemove = input("Enter the name you want to remove:")
print(nametoRemove)
name = ["Ramesh","Rakesh","Suresh"]
for item in name:
if item.lower() == nametoRemove.lower():
name.remove(item)
print(name)
output:
Enter the name you want to remove:ramesh
ramesh
['Rakesh', 'Suresh']

keyerror: in dictionary python3

i'm receiving a key error for the below code. i'm reading a file called names.txt which has both name and age of a person. All names are in lower case but when i do name.lower() function while searching in the dictionary, it's throwing the key error.
fo = open('names.txt' ,'r')
data = fo.readlines()
fo.close()
dicti = {}
for i in data:
new_list = i.split(',')
dicti[new_list[0].lower()] = new_list[1].strip('\n')
name = input ('enter the name to be searched: ')
if name.lower() in dicti.keys():
print (dicti[name])
elif name == 'exit':
quit()
else:
print ('name ' + name.title() + ' not found')
file names.txt data is:
Sophia,35
Emma,28
Olivia,16
Isabella,10
Ava,9
Mia,26
Emily,4
Abigail,33
Can someone please tell me about the error.
Because of this:
if name.lower() in dicti.keys():
print (dicti[name])
You check that the lower-cased name is in the dicti, but then access it as is, without lower-case conversion. The proper code would be:
if name.lower() in dicti.keys():
print (dicti[name.lower()])

Searching Names and phonenumbers

mine is homework question in response to the previous Question i posted on this site:
i redid the code to the following:
import re
people = ["Karen", "Peter", "Joan", "Joe", "Carmen", "Nancy", "Kevin"]
phonenumbers = ["201-222-2222", "201-555-1212", "201-967-1490", 201-333-3333",'201-725-3444", "201-555-1222", "201-444-4656"]
name = raw_input("Enter person's name:")
found = false
for i in range(0, len(people)):
value = people[i]
m = ("(" + name + ".*)",value)
if m:
found = True
print (people[i], phonenumber[i])
else:
print ("No matching name was found.")
My question is how do i tell the program to check if Karen's phone number is the 201-222-2222? And Yes this is a homework assignment. I changed the names and the phone numbers in my acutal program.
When i run this program and type any character all the names and phone number show up that's where i'm having difficutly...
EDITED: Question isn't clear to me.
The following code my help.
1.) First it ask for name then check if it exist in the people list.
2.) Then if it exist it saves it in variable called abc.
3.) After loop is finished it prints the abc which is the name you entered and that person phone number.
import re
people = ["Karen", "Peter", "Joan", "Joe", "Carmen", "Nancy", "Kevin"]
phonenumbers = ["201-222-2222", "201-555-1212", "201-967-1490", "201-333-3333","201-725-3444", "201-555-1222", "201-444-4656"]
name = input("Enter person's name:")
abc = "" # Will store the name and phone number
found = False
for i in range(0, len(people)):
if people[i].lower() == name.lower(): #checks if input name match + use method to lower all char
abc = people[i]+" Has the number "+phonenumbers[i]
value = people[i]
m = ("(" + name + ".*)",value)
if m:
found = True
print (people[i], phonenumbers[i]) # missing letter "s"
else:
print ("No matching name was found.")
print("\n"+abc)
Result

Creating a autocorrect and word suggestion program in python

def autocorrect(word):
Break_Word = sorted(word)
Sorted_Word = ''.join(Break_Word)
return Sorted_Word
user_input = ""
while (user_input == ""):
user_input = input("key in word you wish to enter: ")
user_word = autocorrect(user_input).replace(' ', '')
with open('big.txt') as myFile:
for word in myFile:
NewWord = str(word.replace(' ', ''))
Break_Word2 = sorted(NewWord.lower())
Sorted_Word2 = ''.join(Break_Word2)
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
Basically when I had a dictionary of correctly spelled word in "big.txt", if I get the similar from the user input and the dictionary, I will print out a line
I am comparing between two string, after I sort it out
However I am not able to execute the line
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
When I try hard code with other string like
if ("a" == "a"):
print("The word",user_input,"exist in the dictionary")
it worked. What wrong with my code? How can I compared two string from the file?
What does this mean? Does it throw an exception? Then if so, post that...
However I am not able to execute the line
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
because I can run a version of your program and the results are as expected.
def autocorrect(word):
Break_Word = sorted(word)
Sorted_Word = ''.join(Break_Word)
return Sorted_Word
user_input = ""
#while (user_input == ""):
user_input = raw_input("key in word you wish to enter: ").lower()
user_word = autocorrect(user_input).replace(' ', '')
print ("user word '{0}'".format(user_word))
for word in ["mike", "matt", "bob", "philanderer"]:
NewWord = str(word.replace(' ', ''))
Break_Word2 = sorted(NewWord.lower())
Sorted_Word2 = ''.join(Break_Word2)
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
key in word you wish to enter: druge
user word 'degru'
The word druge doesn't exist in the dictionary
key in word you wish to enter: Mike
user word 'eikm'
('The word','mike', 'exist in the dictionary')
Moreover I don't know what all this "autocorrect" stuff is doing. All you appear to need to do is search a list of words for an instance of your search word. The "sorting" the characters inside the search word achieves nothing.

Resources