I've searched answers on here and tried implementing them but I think that there is some tiny detail I'm missing. I have a very short python code for a program that is supposed to return the initials with periods of a persons input(for their full name). So for example, input is Atticus Leonard Beasley and output should be
A.L.B.
but instead I'm getting:
A.
L.
B.
Here's my code:
def main():
full_name = input("Enter your first, middle, and last name: ")
for ch in full_name:
if ch.isupper():
ch = ch.rstrip('\n')
print (ch,'.', sep='')
main()
FYI, you can do this using split and join:
def main():
full_name = input("Enter your first, middle, and last name: ")
initials = []
for name in full_name.split():
initials.append(name[0])
print('.'.join(initials) + '.')
main()
Or using list comprehension:
def main():
full_name = input("Enter your first, middle, and last name: ")
print('.'.join(name[0] for name in full_name.split())+'.')
main()
I think you can do that in a easier and "more pythonic" way.
full_name = input("Enter your first, middle, and last name: ")
print(''.join([ch[0].upper() + '.' for ch in full_name.split()]))
EXPLANATIONS
Instead of doing a for loop over each letters of the name, you can use split() function to be sure to took care of every words without the extra spaces.
sentence = "hello world"
for ch in sentence.split():
print(ch) # hello
break
Now, you try to verify if the first letter is an uppercase, but if the user enter his name without uppercase, your function does not work. An easier solution will be to extract the first letter of the word ch[0] and automatically add an uppercase: ch[0].upper()
Maybe the one-liner solution is confusing, but most of the python developers use list comprehension over for loops when the solution is easily readable.
EDIT
One more thing, even if you are writing a simple function such as print the initials of a name, you should always write tests accordingly.
A good way to start is to use doctests because it forces you to describe what your function does. Even if you think it's a waste of times, it helps to overcome many problems when your program is getting bigger. I'd be please to help you if you want to try to write your first doctest
Related
I have a task to rearrange a name to last first middle initial. I know for this I can use split() but I'm trying to understand it the way I'm learning it right now which is index and find ect to rearrange it. My question is how would I make it so the program knows what is the first last and middle names since it changes depending on user input. I've tried this and it doesn't work. Is there a way to do this?
Name = input("Enter a name like 'First I. Last: ")
words = Name.find(" ")
first, middle, last = words[1], words[0], words[-1]
find will return the index into a string of that occurence, you can then use that index to slice your original string, find also takes an optional second index to tell it where to start searching from ...
Name = input("Enter a name like 'First I. Last: ")
first_space_index = Name.find(" ")
first_name = Name[:first_space_index]
# find the first space that comes after first_space_index
second_space_index = Name.find(" ",first_space_index + 1)
middle_initial = Name[first_space_index+1:second_space_index]
this is not nearly as good of a solution as just using split but meh ...
You can use the string.split() function to gather the different words in the input. This is preferable to using string.find() as you do not have to slice to find the answer.
name = input("Enter a name like 'First I. Last: ")
words = name.split()
first, middle, last = name[0], name[1], name[2]
Then you can work out the first letter of each 'Hello'[0] -> 'H'
I can't figure out what I need to add to make my code work, this is what I have:
my_string = input("Enter a word: ")
part_to_remove = input("Enter a part of the word to remove: ")
def remove_all_from_string(my_string):
while my_string != "bas":
index = my_string.find(part_to_remove)
return index
print remove_all_from_string(my_string)
I can't figure out what to add next, the test cases tells me to
Use the find function
Use a while loop
Use string concatenation
Use string indexing
Use the len function
Test the code with "bananas"
Test the code by replacing "na"
With the specified test info your code should return "bas"
I don't know what I could possibly do to match these and still make the code work
You can simply use the replace function of strings:
my_string = input("Enter a word: ")
paet_to_remove = input("Enter a part of the word to remove: ")
my_string = my_string.replace(paet_to_remove, "")
I am not going to write that code for you, but I will try to clarify some of the pointers:
use find and string indexing (actually string slicing) to get the part of the string before the part to remove
use find, len, and string slicing to get the part after the part to remove
use string concatenation to combine them and replace the original string
use while and find to continue while the part to remove exists in the string
test the function with parameters "bananas" and "na", and compare the result to "bas", but do not "hard-code" any of that into your function
With those steps, you should be able to write the function on your own.
Similar to the answer of #kevin
my_string = input("Enter a word: ")
paet_to_remove = input("Enter a part of the word to remove: ")
print( ''.join(my_string.split(paet_to_remove)) )
EDIT This was my first post and I completely forgot to show what I had already tried. I wasn't looking for a complete program, just suggestions on methods I could use to concatenate initials. EDIT
I need to create a program that allows a user to input their full name and only prints the initials. This must be done WITHOUT USING .SPLIT OR LISTS
From my hw:
Write a program that gets a string of a person's full name – first, middle, and last name and then displays their initials.
Create a function getInitials().
>>>Enter your full name: James Tiberias Kirk
>>>J.T.K.
Try this one:
n = input('Enter your full name:')
name = ''
for i,j in enumerate(n):
if i == 0:
name+=(j+'.')
elif j == ' ':
name += (n[i+1]+'.')
print(name)
And this is as method:
def getinitials(n):
name = ''
for i,j in enumerate(n):
if i == 0:
name+=(j+'.')
elif j == ' ':
name += (n[i+1]+'.')
return name
print(getinitials(input('Enter your number:')))
Output:
Enter your full name:James Tiberias Kirk
J.T.K.
I ended up figuring it out thanks to all your responses. Our teacher wanted us to only use the narrow scope of what we've learned in class so there was pretty much only one way I would be allowed to write it. I ended up coming up with this:
def getInitials():
fullName=input("Enter your full name:")
initials=''
for ch in fullName:
if ch.isupper():
initials+=ch
initials=str(initials)+"."
print (initials)
if __name__=="__getInitials__":
getInitials()
getInitials()
Assuming you won't deal with names like DeFranco or McDonald, you can iterate over the string and append encountered capital letters (that is, ord('A') <= ord(char) <= ord('Z')) with a dot to your result.
Similar approach that should work on most cases is to append the first character, then look for spaces and append a character next to them.
One solution that technically doesn't use a list:
'.'.join(i for i in x if i.isupper())+'.'
...which uses a generator expression, but that may be closer to a list than the spirit of the assignment. As in the other answer, it fails if a name has more than one capital in the name (McGregor, etc.)
You could use a regex, while returning a generator statement from your getInitials() function, therefore you technically avoid using both split() and a list:
import re
def getInitials(x):
return '.'.join(i for i in re.findall(r'^[A-Z]|(?<=\s)[A-Z]', x)) + '.'
out = getInitials('James Tiberias Kirk McGregor')
Yields:
J.T.K.M.
Note that this method works for names with more than one capital letter per name/word.
I am using the .isalpha function to take an input of a name. It is working but whenever i put on space between name for example a full name John Doe It gives me error.
What ive Tried so far
while not name.isalpha():
print('Entered Name is invalid')
name = input('Please Enter Your Name Sir: ')
if name.isalpha() or name.isspace():
print('Hello Mr.' + name)
select_mmenu('main-menu.txt')
I've tried combining .isalpha and .isspace but it seems not to be working. Need the most simple way to solve this trick
isalpha tests that each member of the string is a letter. isspace tests that each member of the string is a whitespace character. Neither of those is what you want.
Instead you could do:
if all(lett.isalpha() or lett.isspace() for lett in name):
which will pass if every letter is EITHER a letter or a space. Alternatively you can match a regular expression:
import re # at the top of your module
if re.match(r"[\s\w]+$", name):
which is arguably cleaner, and certainly more powerful. The square brackets denote a character class, \s is all whitespaces and \w is all word character, the + means "matches 1 or more times," and the $ is the end of string. [\s\w]+$ then means "one or more characters that are either whitespace or word characters, and nothing afterwards.
It will certainly give you an error because the method isalpha() checks whether the string consists of alphabetic characters only. So if you put a space, the result will return false instead of true, and you will get an error.
Thankyou for the answers. I got it solved without using all() function. I just solved it with simplest basic Python loops
Thankyou Adam Smith because of your answer i got this idea to solve it through that method
con = False
while con!=True:
l=0
strs = input('Enter your Name: ')
for i in strs:
if i.isalpha() or i.isspace():
l += 1
if l == len(strs):
con = True
break
else:
print('Wrong Input')
if con==True:
print(strs)
In this code its basically counting the input lenght and alphabets and space lenght if it match it works. else the while loop continue.
The code written below should give results like below. For example, if input is ' Lion head and Snake tail', output should be - 'LHAST'.
Instead the result is 'LLLLL'. Please check my code. If possible please suggest better practice and help me with better code.
Code is as follows:
#ask for Input
name = input('Input words to make acroname :')
#make all in caps
name = name.upper()
#turn them in list
listname = name.split()
#cycle through
for namee in listname:
#Get the first letter & type in same line
print(name[0],end="")
print()
input (' press a key to move out' )
You may correct your code. Instead of print(name[0]) you should use print(namee[0]) as you want to print the first letter of the word, not the original name.
A good practice is to name the variables the more descriptive you can so as to avoid such typos.
If you want to print the acronym in same line I would suggest to use below code to get variable acronym with the desired output:
phrase = raw_input('Input words to make acronym:')
phrase = phrase.upper()
list_words = phrase.split()
acronym = [word[0] for word in list_words]
acronym = "".join(acronym)
print acronym
You could use str.join with a generator-expression for a one-line solution to the problem:
>>> name = "Lion head and Snake tail"
>>> ''.join(i[0].upper() for i in name.split())
'LHAST'
why?
Well if we start from inside the generator, we are iterating through name.split(). The .split method of a str returns a list of all the different strings which have been found by splitting on what is passed into the method. The default character is a space and since we want the words, this is fine for us.
We then say that for each word i in this list, take the first character from the string with: i[0]. We then convert this to upper case with str.upper().
Then, the final step is to join all these characters together and that is done with the str.join method.
Simply:
print ''.join([P[0] for P in input('Input words to make acroname :').upper().split()])
Use input('') for python 3 and raw_input('') for python 2