How to remove characters from the end or start of every element in a Python list

Question:

I need help removing characters from the start and end of every element in a Python list.
For instance,

list = ["ab1c", "ef2g", "hi3j"]

If this was the list and I wanted to remove the letters from each element by removing the first two and the last character so that the end result would be list = [1, 2, 3], how could I do this?

Asked By: Arvo Ju

||

Answers:

Use re.sub to strip the first two chars and the last one char from the string. Here, . is any character, .* is any character repeated 0 or more times, \1 is the first capture group, that is, whatever was matched inside the parentheses.

import re
lst = ["ab1c", "ef2g", "hi3j"]
lst = [int(re.sub(r'..(.*).', '\1', s)) for s in lst]
print(lst)
# [1, 2, 3]
Answered By: Timur Shtatland

You can try using the .strip() method in python. This would work independent of how many characters are before or after the digit in each string.

import string

list = ["ab1c", "ef2g", "hi3j"]
list = [word.strip(string.ascii_letters) for word in list]
Answered By: Blackgaurd

Strip first two chars and last char:

vals = ["ab1c", "ef2g", "hi3j"]

out = [val[2:-1] for val in vals]

Gives:

['1', '2', '3']

If you also want as ints (in question you ask for [1, 2, 3] as result) then:

out = [int(val[2:-1]) for val in vals]
Answered By: Anentropic

If the number of characters to be removed is fixed as in the original post, you can do the following:

list = ["ab1c", "ef2g", "hi3j"]
for i in range(len(list)):
    list[i]=int(list[i][2])
# list = [1, 2, 3]
Answered By: Lakshya Mahajan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.