Acu
Acu

Reputation: 85

How to make a program separate words by the end of the word?

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

Answers (2)

Malik Brahimi
Malik Brahimi

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

Bhargav Rao
Bhargav Rao

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)

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'

Upvotes: 3

Related Questions