Reputation: 1
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']
I want to remove the first character of each word that starts with 'n'. (for example: 'nnueva', 'nartista', 'nindustrial', etc.)
I tried this but it is removing the first character of the word from ALL words of the list:
lista_A = []
for it in filtered_sent:
for j in it:
if j[0] == 'n':
lista_A.append(it[1:])
Upvotes: 0
Views: 84
Reputation: 578
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:])
Upvotes: 0
Reputation: 21
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)
Upvotes: 1
Reputation: 1
You can try:
list(map(lambda word: word[1:] ,filter(lambda x:(x[0]=="n"),filtered_sent)))
Upvotes: 0
Reputation: 1631
You could try:
filtered = [i[1:] if i[0] == 'n' else i for i in filtered_sent]
Upvotes: 1
Reputation: 15309
Using a built-in str
function:
new_list = [word.removeprefix('n') for word in filtered_sent]
Upvotes: 0