Printing first letter of full name python - python

Hello I'm trying to create a program that takes input and prints out the initials all uppercase but I can't figure out why my program is only printing the first letter of the last item of the list after string is split
this is my code:
full_name = input("Please enter your full name: ")
name = full_name.split()
for item in name:
new_name = item[0].upper()
print(new_name)

You can make a new, empty variable like initials and add the first letter to it
full_name = input("full name: ")
name = full_name.split()
initials = ""
for item in name:
initials += item[0].upper()
print(initials)

I think this can help you:
# get the full name from the user
full_name = input("Enter your full name: ")
# split the name into a list of words
name_list = full_name.split()
# loop through the list of words
for i in range(len(name_list)):
# get the current word
word = name_list[i]
# uppercase the first letter of the word
word = word[0].upper() + word[1:]
# replace the word in the list with the new word
name_list[i] = word
# join the list of words into a string
full_name = " ".join(name_list)
# print the full name
print(full_name)

Related

How to make search input case insensitive for txt file

Right now the code is working but if I don't capitalize the first letter of both first and last name the code will return "error: person not found."
How can I set it up so that no matter how the user inputs the search it will return the requested data?
#Iterate through the lines and save them in a dictionary, with the
#full name as the key
for line in file:
stripped = line.strip()
name = stripped[:stripped.index(',')]
d[name] = stripped[stripped.index(',')+1:].strip()
def main():
#call the input function to read the file
addresses = input_address()
#Get the user option
option = int(input("Lookup (1) phone numbers or (2) addresses: "))
if option == 1:
phone = True
else:
phone = False
#Ask for names and print their information in case they exist, end on blank entry
while True:
name = input("Enter space-separated first and last name: ")
if name == "":
return main()
if name not in addresses:
print("Error: person not found")
else:
display(addresses[name], phone)
main()
Try using:
.capitalize()
For example:
'hello world'.capitalize()
yields,
'Hello World'
So in your case, you would do:
name.capitalize()
then look for it inside addresses.
You can use lower(), upper(), or capitalize(), as long as you attach the chosen method to end of both variables.
Using lower():
for i in range(len(addresses)):
addresses[i] = addresses[i].lower() # Converting array values to lowercase
if name.lower() not in addresses: # Seeing if lowercase variable is in lowercase array
print("Error: person not found")
else:
print("Person found")

how to split string from a integer in python?

My input needs to be for example
name surname, street name 22b, 10000 Zagreb
and it need to output like this:
name and surname: name surname
Street: street name
street number: 22
house number: b
postal code: 100000
place: zagreb
and this is my code
whole_string =input("Person: ")
string_list = whole_string.split(", ")
split_street_and_street_number = string_list[1].split(" ")
postal_code_and_city = string_list[2].split(" ")
print(f"name and surname: {string_list[0]}")
print(f"street: {split_street_and_street_number[0]}")
print(f"street number: {split_street_and_street_number[1]}")
print(f"postal code: {postal_code_and_city[0]}")
print(f"city: {postal_code_and_city[1]}")
Please check out this.
import re
text = '22b'
street_number =" ".join(re.findall("[0-9]+", text))
house_number =" ".join(re.findall("[a-zA-Z]+", text))
print(street_number)
print(house_number)
You can find the index of the first letter and split the string using that index:
def find_index_of_first_letter(text):
for index, value in enumerate(text):
try:
int(value)
except ValueError:
return index
print('No letter in the text')
text = '22b'
first_letter = find_index_of_first_letter(text)
number, letters = text[:first_letter], text[first_letter:]

Can't append the last word from a text file to a list

I want to make a list of words contained in a text file. But my code prints all but the last word of the file. What am I doing wrong ?
def word_map(file):
text = file.read()
word = "" # used as a temporary variable
wordmap = []
for letter in text:
if letter != " ":
word = word+letter
else:
wordmap.append(word)
word = ""
return set(wordmap)
Just use wordmap = text.split(" ")
I hope this helped, good luck.
When exiting the loop you are not appending the last word, just try this:
def word_map(file):
text = file.read()
word = "" # used as a temporary variable
wordmap = []
for letter in text:
if letter != " ":
word = word+letter
else:
wordmap.append(word)
word = ""
wordmap.append(word)
return set(wordmap)
I think you're missing a final :
wordmap.append(word)
Because if your text file does not end with a space, it won't be appended

How to match words in a list with user input in python?

I am working on program which takes user input and replaces the words in a list with 'x'.
eg is the word is sucks and user input is "this word is sucks". the output should be "this word is xxxxx.
this is what i have so far. how can i access the elements in the list and match with the user input?
def main():
message = []
words = ['drat','crap','sucks']
counter = 0
userInput = str(input("Enter The Sentense: "))
truncatedInput = userInput[:140]
sentence = truncatedInput.split()
for i in range(len(sentence)):
def main():
final_message = []
words = ['drat','crap','sucks']
counter = 0
userInput = input("Enter The Sentense: ") # use raw_input if you're using python2.X
truncatedInput = userInput[:140]
sentence = truncatedInput.split()
for word in sentence:
if word in words:
word = 'x' * len(word)
final_message.append(word)
print ' '.join(final_message)

Grouping string input by count

I'm trying to do a question out of my book and it asks:
Implement function names that takes no input and repeatedly asks the
user to enter a student's first name. When the user enters a blank
string, the function should print for every name, the number of
students with that name.
Example usage:
Usage:
names()
Enter next name: Valerie
Enter next name: Bob
Enter next name: Valerie
Enter next name: John
Enter next name: Amelia
Enter next name: Bob
Enter next name:
There is 1 student named Amelia
There are 2 students named Bob
There is 1 student named John
There are 2 students named Valerie
So far I have this code:
def names():
names = []
namecount = {a:name.count(a) for a in names}
while input != (''):
name = input('Enter next name: ')
names = name
if input == ('')
for x in names.split():
print ('There is', x ,'named', names[x])
I'm really lost here and any input would help out tons. Also if possible please explain how to fix my code
There are a lot of issues with namings in your function, you are using such variables like 'names' that is used for function name as well as 'input' that is a python function name for reading user input - so you have to avoid using this. Also you defining a namecount variable as a dict and trying to initialize it before fill. So try to check solution below:
def myFunc():
names = []
name = ''
while True: #bad stuff you can think on your own condition
name = raw_input('press space(or Q) to exit or enter next name: ')
if name.strip() in ('', 'q', 'Q'):
for x in set(names):
print '{0} is mentioned {1} times'.format(x, names.count(x))
break
else:
names.append(name)
myFunc()
OR:
from collections import defaultdict
def myFunc():
names = defaultdict(int)
name = ''
while True: #bad stuff you can think on your own condition
name = raw_input('press space(or Q) to exit or enter next name: ')
if name.strip() in ('', 'q', 'Q'):
for x in set(names):
print '{0} is mentioned {1} times'.format(x, names[x])
break
else:
names[name] += 1
I rewrote your function for you:
def names():
names = {} # Creates an empty dictionary called names
name = 'cabbage' # Creates a variable, name, so when we do our while loop,
# it won't immediately break
# It can be anything really. I just like to use cabbage
while name != '': # While name is not an empty string
name = input('Enter a name! ') # We get an input
if name in names: # Checks to see if the name is already in the dictionary
names[name] += 1 # Adds one to the value
else: # Otherwise
names[name] = 1 # We add a new key/value to the dictionary
del names[''] # Deleted the key '' from the dictionary
for i in names: # For every key in the dictionary
if names[i] > 1: # Checks to see if the value is greater for 1. Just for the grammar :D
print("There are", names[i], "students named", i) # Prints your expected output
else: # This runs if the value is 1
print("There is", names[i], "student named", i) # Prints your expected output
When doing names():
Enter a name! bob
Enter a name! bill
Enter a name! ben
Enter a name! bob
Enter a name! bill
Enter a name! bob
Enter a name!
There are 3 students named bob
There are 2 students named bill
There is 1 student named ben
Let's analyse your code:
def names():
names = []
namecount = {a:name.count(a) for a in names}
while input != (''):
name = input('Enter next name: ')
names = name
if input == ('')
for x in names.split():
print ('There is', x ,'named', names[x])
There seem to be a few problems, let's list them
The while loop's conditional
What you want to do check if input from user is '' (nothing)..
input is a built-in function for getting input from user, so it never will be ('').
The names = name statement
What you want to do is add name to the list names.
Here you are changing names to a string, which isn't what you want.
The if's conditional
same as 1.
The for loop
let's ignore.. just not valid.. here..
We fix these problems as follows(solution has same numbering as problem above that it solves)
Change the conditional to something like name != ''.
Also, before the loop begins, you need to get input once for this to work, which in this case has a bonus, the first input can have a different prompt.
Use names.append(name) to add name to names.
Same as 1.
Just look at the for loop below...
Try this
def names():
names = []
name = input('Enter a name: ').strip() # get first name
while name != '':
names.append(name)
name = raw_input('Enter next name: ').strip() # get next name
for n in set(names): # in a set, no values are repeated
print '%s is mentioned %s times' % (n, names.count(n)) # print output
def names():
counters = {}
while True:
name = input('Enter next name:')
if name == ' ':
break
if name in counters:
counters[name] += 1
else:
counters[name] = 1
for name in counters:
if counters[name] == 1:
print('There is {} student named {}'.format(counters[name],name))
else:
print('There are {} student named {}'.format(counters[name],name))
names()

Categories