Python. Remove part of strings of sublists starting with a word

Helo I want to remove from a list of sublists of string items, a specific word which some items are starting with. I got that so far, but it is working with flatten lists, I do not know how to make it for sublists. what it does split the strings that contains the word and keep the latest part of it, so the word is removed.

#inputlist
lolol=[["beauty.numberone","beauty.full","awful.x"],["beauty.numberone","beauty.full","awful.x"]]
#stringstartingwith=["beauty.","awful"]
#replacement=["",""]
#desiredresult=[["numberone","full","x"],["numberone","full","x"]]

#code I tried
lolx=[i.split('beauty.')[1] if 'beauty' in i else i for i in lolol]

Hi @ruben.romero,

You can do something like this if you would like to stick to list comprehension:

Or you can stick to traditional looping if you are just starting out with Python.

1 Like

what if I want to add more than one word to remove?is possible to add more or would I need to repeat this code for each word to remove? I want also “awful.” to be removed

@ruben.romero Look into the Regular Expressions (Regex):

#inputlist
lolol=[["beauty.numberone","beauty.full","awful.x"],["beauty.numberone","beauty.full","awful.x"]]
words = ["beauty.","awful."]
splits = "|".join(words)

import re

OUT = []
for lol in lolol:
	temp = []
	for i in lol:
		temp.append(re.split(splits, i)[1])
	OUT.append(temp)
2 Likes

You have a few options here. You can check each key word individually (within the same for i in lol: loop) and split the string whenever a key word is included or you can add another loop for each key word and remove whatever comes up.

I would use the latter approach with string.replace as it’s more direct.

EDIT: RegEx is also a good option. @AmolShah :+1:

2 Likes

I am not sure what is wrong but the previous script which uses split function, crashed my computer consuming 22GB RAM and this second gave me this warning out of ange
image

@Nick_Boyts thanks very much it worked and quickly, I do not have a clue why the other wonderful solutions of @AmolShah did not work to me, perhaps there are exceptions that I do not know