How to take the nth digit of a number in python

前端 未结 7 1509
梦毁少年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:12

    First treat the number like a string

    number = 9876543210
    number = str(number)
    

    Then to get the first digit:

    number[0]
    

    The fourth digit:

    number[3]
    

    EDIT:

    This will return the digit as a character, not as a number. To convert it back use:

    int(number[0])
    

提交回复
热议问题