Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice every string in list in Python

I want to slice every string in a list in Python.

This is my current list:

['One', 'Two', 'Three', 'Four', 'Five']

This is the list I want for result:

['O', 'T', 'Thr', 'Fo', 'Fi']

I want to slice away the two last characters from every single string in my list.

How can I do this?

like image 483
Peter Avatar asked Jul 14 '26 08:07

Peter


2 Answers

Use a list comprehension to create a new list with the result of an expression applied to each element in the inputlist; here the [:-2] slices of the last two characters, returning the remainder:

[w[:-2] for w in list_of_words]

Demo:

>>> list_of_words = ['One', 'Two', 'Three', 'Four', 'Five']
>>> [w[:-2] for w in list_of_words]
['O', 'T', 'Thr', 'Fo', 'Fi']
like image 121
Martijn Pieters Avatar answered Jul 16 '26 11:07

Martijn Pieters


You can do:

>>> l = ['One', 'Two', 'Three', 'Four', 'Five'] 
>>> [i[:-2] for i in l]
['O', 'T', 'Thr', 'Fo', 'Fi']
like image 31
heemayl Avatar answered Jul 16 '26 12:07

heemayl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!