7

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?

3
  • 4
    Please try to demonstrate minimal efforts before you ask for a solution. Commented Feb 10, 2016 at 12:13
  • 1
    Can you slice the last two characters from a string? Commented Feb 10, 2016 at 12:15
  • 2
    I think we should discourage this kind of questions by not providing ready solution, this won't be really helping OP, at least not for his future. Commented Feb 10, 2016 at 12:15

3 Answers 3

14

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']
Sign up to request clarification or add additional context in comments.

Comments

3

You can do:

>>> l = ['One', 'Two', 'Three', 'Four', 'Five'] 
>>> [i[:-2] for i in l]
['O', 'T', 'Thr', 'Fo', 'Fi']

Comments

2
x=['One', 'Two', 'Three', 'Four', 'Five']
print map(lambda i:i[:-2],x)  #for python 2.7
print list(map(lambda i:i[:-2],x)) #for python 3

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.