+ 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?
4 Réponses
+ 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
+ 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))])
+ 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.
+ 1
thanks All for your replies.
Choe could you explain your pythonic version? I’d like to understand what happens