Remove the last text in list of strings in Python?

Hello,

I got for example this list [abracadabra,cabra,malacabra,caca] and I want to remove the part of the strings that are ending in this string text “bra”, so I would get a result like this in the string list: [abracada,ca,malaca,caca]

The most similar OOTB node is String.TrimTrailingWhitespace, but instead of space I need specific string to remove.

There are a number of ways to go about this. There is a python method called rstrip() that does exactly what you’re looking for. Or you could get a little creative with some node logic; Example: Split the strings at their last three characters, check to see if those chars == "bra" and return either the original or split string depending on that result.

1 Like

so it would be something like that?:

newlist=list.rstrip(“bra”)

I get this warning for a list AttributeError: ‘list’ object has no attribute ‘rstrip’

You would use the method on the string, so you have to loop through each string in the list, but yes.

1 Like

Need to tell python that it needs to loop over the objects in the list via a for loop or list comprehension.

Alternatively you can wrap the python in a custom node to allow dynamo to handle the looping for you.

You can try this:

lst = ['abracadabra','cabra','malacabra','caca']
OUT = [i[:-3] if i.endswith('bra') else i for i in lst]

it works if I remember to change the number of characters to remove from the end based on the string to remove hehe, I can live with it, thanks

To avoid that, use the len function:

lst = ['abracadabra','cabra','malacabra','caca']
to_remove = 'bra'
OUT = [i[:-len(to_remove)] if i.endswith(to_remove) else i for i in lst]
2 Likes

OUT = [ i.rstrip(“bra”) for i in IN[0] ]

2 Likes