remove the last two characters from strings in list using python

Viewed 66

I have a very complicated problem. At least my python skills are not enough to solve it and I need help or at least ideas on how to solve this problem.

I have a huge list of words that looks like this:

words_articles=['diao','carrosos', 'cidadea', cidadesas']

I need to append into another list the last or the last two characters of each string into a new list, because they are these words' articles: 'a', 'o', 'as', 'os'

my result should be two lists like the following:

words=['dia','carros', 'cidade', 'cidades']

articles=['o', 'os','a','as']

I have no idea how to solve this. I just know that I have to loop through each string but from this stage on I don't know what to do.

words_articles=['diao','carrosos', 'cidadea', 'cidadesas']
words=[]
articles=[]

for y in words:
    for x in y:

What should I do next after this?

2 Answers

You can test the last letter

words_articles=['diao','carrosos', 'cidadea', 'cidadesas']
words=[]
articles=[]

for word in words_articles:
  if word[-1] == 's':
    words.append(word[:-2])
    articles.append(word[-2:])
  else:
    words.append(word[:-1])
    articles.append(word[-1:])

print(words)
print(articles)

Out:

['dia', 'carros', 'cidade', 'cidades']
['o', 'os', 'a', 'as']

You probably want the 'words' and 'articles' variables to be sets to prevent duplication:

words_articles=['diao','carrosos', 'cidadea', 'cidadesas']
words=set()
articles=set()

for word in words_articles:
    suffix_size = 2 if word.endswith("s") else 1
    words.add(word[:-suffix_size])
    articles.add(word[-suffix_size:])

Output would be:

{'carros', 'cidade', 'dia', 'cidades'}
{'a', 'as', 'os', 'o'}
Related