How to take the nth digit of a number in python

前端 未结 7 1530
梦毁少年i
梦毁少年i 2020-11-30 10:42

I want to take the nth digit from an N digit number in python. For example:

number = 9876543210
i = 4
number[i] # should return 6

How can

7条回答
  •  醉酒成梦
    2020-11-30 11:14

    Ok, first of all, use the str() function in python to turn 'number' into a string

    number = 9876543210 #declaring and assigning
    number = str(number) #converting
    

    Then get the index, 0 = 1, 4 = 3 in index notation, use int() to turn it back into a number

    print(int(number[3])) #printing the int format of the string "number"'s index of 3 or '6'
    

    if you like it in the short form

    print(int(str(9876543210)[3])) #condensed code lol, also no more variable 'number'
    

提交回复
热议问题