I created a Python function that takes an argument, fullname, gets fullname's initials and prints them out capitalized. But there's a problem with my code - it only works with two names. It breaks if the fullname has a middle name, i.e. Daniel Day Lewis.
Here is what I tried:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
second = name_list[1][0]
return(first.upper() + second.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
Obviously this attempt only includes two variables, one for the first name and one for the second name. If I add a third variable, like this:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
second = name_list[1][0]
third = name_list[2][0]
return(first.upper() + second.upper() + third.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
I get:
IndexError: list index out of range on line 10
(which is the line)
third = name_list[2][0]
Of course this function does work if I change fullname to "Ozzie Smith Jr". But my function has to work regardless of whether there are 1, 2, 3, or 4 names in fullname. I need to say something like:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
#if fullname has a second name:
second = name_list[1][0]
#if fullname has a third name:
third = name_list[2][0]
#if fullname has one name:
return(first.upper())
#if fullname has two names:
return(first.upper() + second.upper())
#if fullname has three names:
return(first.upper() + second.upper() + third.upper())
#if fullname has three names:
return(first.upper() + second.upper() + third.upper + fourth.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
How do I say "if fullname has a second name or third name or fourth name, return the uppercase initial" in Python? Or am I on the right track? Thank you.
You can make use of a list comprehension:
s = ''.join([x[0].upper() for x in fullname.split(' ')])
edit: should probably explain a little more
list comprehensions allow you to build a list as you iterate.
So first we build a list by splitting fullname with a space fullname.split(' '). As we get those values, we take the fist letter x[0] and uppercase it .upper(). Finally we join the list into one with no spaces ''.join(...).
This is a nice one liner that's really fast and will pop up in various forms as you continue working with python.
How about something like:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
initials = ""
for name in name_list: # go through each name
initials += name[0].upper() # append the initial
return initials
This is my answer:
Splitting the string into a list
Iterate through elements using range and i
Taking index 0 for each element during iteration (Hence words[i][0])
words[i][0].upper for the upper case requirement for the question
def initials(phrase):
words = phrase.split()
result = ""
for i in range(len(words)):
result += words[i][0].upper()
return result
print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS
This should work
map(str.upper, zip(*the_persons_name.split())[0])
the other variance of one liner as below, we can join all the initials 1st then do the upper 1 shot at last
''.join(i[0] for i in a.split()).upper()
def initials(name):
words = name.split()
result = ""
for word in words:
result += word[0].upper()
return result
Related
I want to capitalize a char in a string, specifically using a for loop. Can someone show how this is done using the code below. or something simpler but still using for loop iterations
name = input("Enter name")
name_list = list(name)
for i in range(len(name_list)):
if i == name_list[3]:
name_list = name_list[3].upper
else:
name_list += i
print(name_list)
Assuming this is Python, you can it by assigning the newly uppercase letter to the list at the lowercase letter's index. For example, if we want to make every third letter upper case in the string enter name, then:
name = "enter name"
name_list = list(name)
for i in range(len(name_list)):
if i % 3 == 0:
name_list[i] = name_list[i].upper()
print(''.join(name_list))
Output:
EntEr NamE
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
initials = ""
for name in name_list: # go through each name
initials += name[0].upper() # append the initial
## ^^ what is happening here?
return initials
What is the += in this context? Is it incrementing the value in the list?
The line initials += name[0].upper() # append the initial adds the first character to a string, the process:
Split a string into a list (So john doe becomes ['john', 'doe'])
Iterate over each item in that list
For each item in that list, append to the empty string the first character, capitialized
For example, for john, get the first character j and capitalize it as J
Return the initials (JD in this case)
I'm fairly new to python, so I'm trying to take a string with two words that could be a mix of upper and lower case separated by 1 or more spaces (like in my example with the variable name) and turn it into a string like
"Banana Split", where the first letter of each word is in caps and the rest are lower, spaces removed except for one in between the two words. Here's what I got:
name = "banAna sPlit"
name = name.lower()
name = name.split()
for i in name:
i = i[0].upper() + i[1:]
name = " ".join(i)
print(name)
Why does this only split the first word? Doesn't the for loop address each element of the list, which contains "banana" and "split"? How should I fix this?
Try using title() function!
name = "banAna sPlit"
name = name.lower()
name = name.split()
array = []
for i in name:
array.append(i.title())
name = " ".join(array)
print(name)
This also removes the whitespace between words!
You can create a new list with the adjustments you are looking for.
name = "banAna sPlit"
name = name.lower()
name = name.split()
name = [i[0].upper() + i[1:] for i in name]
name = " ".join(name)
print(name)
i takes on the value of the element, but assigning to i will reassign the variable, and not assign to the value of the list. Instead, enumerate the list so you get an index and a value, then assign the new value to the list with the index:
for i, v in enumerate(name):
name[i] = v[0].upper() + v[1:]
name = " ".join(name)
Assigning to i doesn't assign to the list element, it just assigns to the variable.
Use a list comprehension to create a new list with the modifications.
name = [i[0].upper() + i[1:] for i in name]
name = " ".join(name)
This takes into account more than two spaces
name = "banAna sPlit"
names = name.split(' ')
names = str([" ".join(filter(None,names))]).title()
print(names)
>>> ['Banana Split']
This is my code. I'm trying to take an input from the user, put it in a list, then check every elements if it is less than 5 characters.
It's supposed to print all the names under such condition but it only returns the last element that fits the condition.
My code:
#function to check the length of the characters
def test(names):
for x in names:
if len(x) <= 5:
print(x)
return x
#ask input from the user
names = input("Enter names: ").split()
#convert to a list
lst = list(names)
#container
viewList = test(names)
#print names under 5 characters
print("Names under five characters: ", viewList)
#just to test the elements in the list
print(names)
The Output:
Enter names: kent monique jeff ban
kent
jeff
ban
Names under five characters: ban
['kent', 'monique', 'jeff', 'ban']
As you can see, it only prints the last element. What mistake am I doing here?
Use this
#function to check the length of the characters
def test(names):
a = []
for x in names:
if len(x) <= 5:
print(x)
a.append(x)
return a
#ask input from the user
names`enter code here` = input("Enter names: ").split()
#convert to a list
lst = list(names)
#container
viewList = test(names)
#print names under 5 characters
print("Names under five characters: ", viewList)
#just to test the elements in the list
print(names)
Using a generator instead you could use:
# function to check the length of the characters
def test(names):
for x in names:
if len(x) <= 5:
yield x
# ask input from the user
names = input("Enter names: ").split()
# container
viewList = [name for name in test(names)]
# print names under 5 characters
print("Names under five characters: ", viewList)
# just to test the elements in the list
print(names)
Note that after using split() your result is already a list, so converting it to a list is redundant.
An often used method is filter(...) as in
viewList = list(filter(lambda x: len(x) <= 5, names))
I have gotten about 80% of this program done but I cannot for the life of me figure out how to replace the vowels with asterisks and print the new string.
Instructions are as follows:
prompt the user to enter his/her first name.
output the number of letters in the name.
print all of the letters in the name separated by a space, all on one line.
print the name in all upper case.
use one slicing to make a new string from the name, but without the first and last letters.
print this new string.
pass the original name to a function named str_func.
inside the str_func function:
replace the vowels in the name with asterisks
return the modified name back to main
back in main, print the string returned by str_func.
My code so far:
def main():
name = input('Enter your first name: ')
print(name)
### print name with spaces in between characters
spaces = ''
for ch in name:
spaces = spaces + ch + ' '
print(spaces[:-1]) # to get rid of space after e
print('name in caps is,',name.upper()) # print name in all caps
print('After chopping the name we get',name[1:4])
print(str_func)
def str_func():
str_func = name.replace('a','*')
return str_func
main()
A friend of mine has helped somewhat stating I have issues with my str_func function:
The function is supposed to take the name as an argument in the main function when you call it.
You don't print it. You call it, something like this:
new_name = str_func(name)
Define str_func() like this. I put in some pseudocode for you.
def str_func(name):
###make a string containing the vowels
###loop through the name
###replace vowel if found with *
### after loop, return the name
Please help!!
This may help you.
import re
def main():
#Using "raw_input" instead of "input"
name = raw_input('Enter your first name: ')
print(name)
### print name with spaces in between characters
spaces = ''
for ch in name:
spaces = spaces + ch + ' '
print(spaces[:-1]) # to get rid of space after e
print('name in caps is,',name.upper()) # print name in all caps
print('After chopping the name we get',name[1:4])
new_name=str_func(name)
print(new_name)
def str_func(value):
#re is regular expression module. It will match string "Guido" and re.IGNORECASE makes it case insensitive.
#When value will Guido, it will be returned as it is.
if re.match(r"Guido",value,re.IGNORECASE):
return value
else:
for x in "aeiou":
value= value.replace(x, '*')
return value
main()
Output
C:\Users\Dinesh Pundkar\Desktop>python a.py
Enter your first name: Guido
Guido
G u i d o
('name in caps is,', 'GUIDO')
('After chopping the name we get', 'uid')
Guido
C:\Users\Dinesh Pundkar\Desktop>python a.py
Enter your first name: Jfalcone
Jfalcone
J f a l c o n e
('name in caps is,', 'JFALCONE')
('After chopping the name we get', 'fal')
Jf*lc*n*
C:\Users\Dinesh Pundkar\Desktop>
Others have provided a solution to your immediate problem but I’ll try to improve the whole code. I don't know what functions you've been introduced to so I might provide both a naive and a pythonic implementation for each steps.
To start with, you did not answered question 2: print the length of the input string. You can either count them manually:
size = 0
for letter in name:
size += 1
print(size)
or use the built-in function len:
size = len(name)
print(size) # or print(len(name)) if you don't need the intermediate variable
You can improve the spacing of your input using the join method of strings:
spaced = ' '.join(name)
print(spaced) # or print(' '.join(name)) if you don't need spaced
You can pass any iterable of strings to join and a string fits.
Your slicing take the second, third and fourth letter of your input. No matter what its length is. You need to either make use of the lenght of the string computed earlier:
sliced = name[1:size-1]
print(sliced)
or use negative numbers in the slice notation to count from the end of the string:
print(name[1:-1])
You're required to write a function and call it to mutate the string. You’ll thus have to call it like:
mutated = str_func(name)
print(mutated)
The function can either iterate over the original string:
def str_func(original):
copy = ''
for letter in original:
if letter in 'auieoy':
copy += '*'
else:
copy += letter
return copy
or use replace:
def str_func(original):
copy = original
for vowel in 'aeuioy':
copy = copy.replace(vowel, '*')
return copy
You can even use translate which can be a better fit in a more general use:
def str_func(original):
from string import maketrans
vowels = 'auieoy'
return original.translate(maketrans(vowels, '*' * len(vowels)))
Assembling all that together:
from string import maketrans
def do_stuff():
name = input('Enter your first name: ')
print('Your input is', name)
print('It\'s length is', len(name))
print('Adding spaces:', ' '.join(name))
print('Capitalizing it:', name.upper())
print('Chopping it:', name[1:-1])
mutated = str_func(name)
print('Removing vowels:', mutated)
def str_func(original):
vowels = 'auieoy'
return original.translate(maketrans(vowels, '*' * len(vowels)))
if __name__ == '__main__':
do_stuff()
test = 'qwertyuiopasdfghjklzxcvbnm'
def changestring(string):
for x in 'aeiou':
string = string.replace(x, '*')
return string
changestring(test)
'qw*rty***p*sdfghjklzxcvbnm'
Is this what you are trying to do?