pythonint

How to take the nth digit of a number in python


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 I do something like that in python? Should I change it to string first and then change it to int for the calculation?


Solution

  • 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])