+ 1

How can I "read" specific parts of numbers (int) in Python?

I want to read the parts of numbers. So if you have 123, I want to use the 1 the 2 and the 3 separately. As if you would use a = 123 print([0] #output: 1 Can I do this in a different way than converting them to strings?

25th Jun 2019, 11:50 AM
Brave Tea
Brave Tea - avatar
4 Answers
+ 7
Using a list comprehension like this: num = 123 lst_int = [int(x) for x in str(num)] print(lst_int) # output: [1, 2, 3] # then you can iterate on this list or pick position with index or slice: # pick first and last digit: print(lst_int[0]) # -> 1 print(lst_int[-1]) # -> 3
25th Jun 2019, 2:08 PM
Lothar
Lothar - avatar
+ 3
no str l = [] n = 123 while n: l.insert(0,n%10) n//=10 print(l) more pythonic version though is better print([*map(int,str(123))])
25th Jun 2019, 6:26 PM
Choe
Choe - avatar
+ 2
You can do a = 123 b, c, d = a//100, (a%100)//10, a%10 print(b, c, d) #1 2 3 but I don't think there's a way of just picking the first digit without turning it into a string or doing some mathematical manipulation.
25th Jun 2019, 12:05 PM
Russ
Russ - avatar
+ 1
thanks All for your replies. Choe could you explain your pythonic version? I’d like to understand what happens
26th Jun 2019, 8:35 AM
Brave Tea
Brave Tea - avatar