Home > Back-end >  Removing the first char some words on a list in Python
Removing the first char some words on a list in Python

Time:10-31

Could someone please help me with this code in python:

I have the following list.

filtered_sent = ['colombia', 'nnueva', 'revolución', 'nindustrial', 'npropuestas', 'foco', 'tecnologías', 'convergentes', 'ne', 'industrias', 'nvolumen', 'ncolombia', 'nartista', 'federico', 'uribe', 'npropuestas', 'foco', 'tecnologías', 'convergentes', 'ne', 'industrias', 'ntomo', 'ncolombia', 'nueva', 'nrevolución', 'nindustrial', 'vicepresidencia', 'república', 'colombia', 'ministerio', 'ciencia', 'tecnología', 'innovación', 'elías', 'niño', 'ruiz', 'jean', 'paul', 'allain', 'josé', 'alejandro', 'montoya', 'juan', 'luis']

and I want to remove the first character of each word that starts with 'n'. (for example: 'nnueva', 'nartista', 'nindustrial', etc)

I have tried this code but it is removing, from ALL words of the list, the first character of the word so it doesn´t work for me:

lista_A = [] 
for it in filtered_sent:
    for j in it:
        if j[0] == 'n':
            lista_A.append(it[1:])

I would really appreciate if someone could show me my mistake, thanks :)

CodePudding user response:

You could try:

filtered = [i[1:] if i[0] == 'n' else i for i in filtered_sent]

CodePudding user response:

Using a built-in str function:

new_list = [word.removeprefix('n') for word in filtered_sent]

CodePudding user response:

You can try:

list(map(lambda word: word[1:] ,filter(lambda x:(x[0]=="n"),filtered_sent)))

CodePudding user response:

There is some logical issue with your code in if block.

It's better to compare both index and first char of the word.

This code works.

lista_A = [] 
for it in filtered_sent:
    for i,j in enumerate(it):
        if j == 'n' and i == 0:
            lista_A.append(it)
        
print(lista_A)

CodePudding user response:

Answering the question, the mistake is the second for loop ("for j in it:"). There's no need to iterate through each letter of each word. Instead of checking only if the first letter of each word is equal to 'n', your code is checking if any letter of the word is equal to 'n'. At each iteration of the inner for loop, both j and j[0] are a reference to the same specific letter.

You can add some print statements to your code to better understand what is happening.

lista_A = [] 
for it in filtered_sent:
    for j in it:
        print(f'it: {it}')
        print(f'j: {j}')
        print(f'j[0]: {j[0]}')
        if j[0] == 'n':
            lista_A.append(it[1:])

Try removing the second for loop, and change the if clause to check the first character of the word:

lista_A = [] 
for it in filtered_sent:
  if it[0] == 'n':
    lista_A.append(it[1:])
  • Related