Python, how to crop a string?

Hi,

I can’t find the way to crop this list :
/project1/FX_Smoke/out1
/project1/FX_twist/out1
/project1/FX_wall/out1
/project1/FX_Stroke/out1
/project1/FX_pixels/out1

to :
FX_Smoke
FX_twist
FX_wall
FX_Stroke
FX_pixels

Like Substitute can do.
Here is the way to obtain this list

[code]list = (op(‘switch1’).inputs)
for n in list :

print(n)[/code]

I tried to do this:

[code]list = (op(‘switch1’).inputs)
for n in list :

print(n[10:])[/code]

but doesn’t work because “object is not subscriptable”.

Okay, I find it :

[code]list = (op(‘switch1’).inputs)
for n in list :

print(str(n)[10:])[/code]

But now, all my “FX_######” are characters (strings), how could I turn them into a list?

You could do this with a list comprehension:

[ str( item )[ 10: ] for item in op( 'switch1' ).inputs ]

List comprehensions are a kind of way of doing a for loop in a list. In this example the code has the operation first, followed by the for loop. Normally the operation would be inside of the loop, but here we set it first. The entire operation is enclosed in square braces and returns a list. Take a look at this example to see how it works:
base_list_comprehension_example.tox (558 Bytes)

Yes, list comprehension + if you just want the middle bit, you can use split:

[str(item).split('/')[2] for item in op('switch1').inputs]

split breaks up the string into a list divided by the chosen character, so…
[‘’ ,‘project1’, ‘FX_Smoke’, ‘out1’]
Since the item you want is always at index two, you just pick [2].

Cool ! Thank you guys, really helpful :wink: