Search code examples
pythonstringintegerdigits

How to manipulate digits within an integer/string?


I am looking for a general way to refer to particular digits in a integer or string, I need to be able to perform different operations on alternating digits and sum the result of all of those returned values.

Any help is much appreciated

Oh and I am a complete beginner so idiot-proof answers would be appreciated.

I will elaborate, is there any inbuilt function on Python that could reduce an integer into a list of it's digits, I have looked to no avail and I was hoping someone here would understand what I was asking, sorry to be so vague but I do not know enough of Python yet to provide a very in-depth question.


Solution

  • If you're starting with an integer, first convert it to a string; you can't address the digits within an integer conveniently:

    >>> myint = 979
    >>> mystr = str(myint)
    >>> mystr
    '979'
    

    Address individual digits with their index in square brackets, starting from zero:

    >>> mystr[1]
    '7'
    

    Convert those digits back to integers if you need to do math on them:

    >>> int(mystr[1])
    7
    

    And if you're just doing a numerological summation, list comprehensions are convenient:

    >>> sum( [ int(x) for x in mystr ] )
    25
    

    Just keep in mind that when you're considering individual digits, you're working with strings, and when you're doing arithmetic, you're working with integers, so this kind of thing requires a lot of conversion back and forth.