Reputation: 85
I know the question sounds a little tricky or not really clear but I need a program, which would separate names. Since I am not from an English speaking country, our names either end in s (for males) or in e and a (for girls)
How do I make Python separate words by their last letter? I guess this would explain more.
Like there are three names: "Jonas", "Giedre", "Anastasija".
And I need the program to print out like this
MALE: Jonas
FEMALE: Anastasija, Giedre
I started up the program and so far I have this:
mname = []
fname = []
name = input("Enter a name: ")
That's really all I can understand. Because I'm not familiar with how to work the if
function with the last letter.
Upvotes: 0
Views: 74
Reputation: 16711
If you're entering the names at once, you'll need to split them by whitespace checking the ends:
names = input('Enter names: ') # string of names to split by spaces
fname = [n for n in names.split() if n[-1] in ('a', 'e')] # females
mname = [n for n in names.split() if n[-1] == 's'] # now male names
Upvotes: 0
Reputation: 52111
You could use negative indexes to acess the last element of the string
name = input("Enter a name: ")
if name[-1] in ('a','e'):
fname.append(name)
elif name[-1] == 's':
mname.append(name)
As you can see, -1
is the last character of a string.
Quoting from the python tutorial
Indices may also be negative numbers, to start counting from the right:
>>> word[-1] # last character 'n'
Upvotes: 3