0

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.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Acu
  • 85
  • 1
  • 7

2 Answers2

3

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)

Image

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'

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
0

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
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70