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?
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]
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]
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]
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]
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?
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]
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]
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]
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]