Search code examples
pythonstringnlp

remove the last two characters from strings in list using python


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?


Solution

  • 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']