-2

I would like to remove the first two characters from each element (which are currently ints) that i have in a list. This is what i have:

lst = [2011,2012,3013]

I would like to get this

lst= [11,12,13]

I do not want a solution with some sort of replace 20 or 30 with '' however.

skimchi1993
  • 189
  • 2
  • 9

4 Answers4

3

Given source= [2011,-2012,-3013] :

Result as ints, unsigned:

dest = [abs(x)%100 for x in source]

Result as ints, signed

dest = [(abs(x)%100)*(1 if x > 0 else -1) for x in source]

Result as strings, unsigned (preserves leading zeroes):

dest = list(map(lambda x : str(x)[-2:],source)

Result as strings, signed (preserves leading zeroes):

dest = list(map(lambda x : ("-" if str(x)[0]=="-" else "")+str(x)[-2:],source))
Attersson
  • 4,755
  • 1
  • 15
  • 29
1

You can use:

list = [abs(number)%100 for number in list]

And it's a bad practice to name lists list. Use another name.

1

You can use module by 100,like:

my_list= [2011,2012,3013]
expected_list = [i%100 for i in my_list]

If you have negative numbers in my_list:

expected_list=[abs(i)%100 for i in my_list]

Or use string slicing:

expected_list = [int(str(i)[2:]) for i in my_list] #[2:],because you want to remove first two numbers

Please try avoid using reserved keywords as you variable name, as you have used list as your variable name.

Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
0

Modulo:

just modulo each element with like 100

list= [2011,2012,3013]
for i in range(len(list)):
    list[i] %= 100
Tollpatsch
  • 304
  • 4
  • 13