Reputation: 3501
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.
Upvotes: 2
Views: 33976
Reputation: 15167
I'm not going to claim this is the best answer, but it meets your requirements:
In [1]: x = 1003998484
In [2]: [int(y) for y in str(x)]
Out[2]: [1, 0, 0, 3, 9, 9, 8, 4, 8, 4]
Or, if your input is already a string you can omit the str()
cast:
In [1]: x = '482898477382'
In [2]: [int(y) for y in x]
Out[2]: [4, 8, 2, 8, 9, 8, 4, 7, 7, 3, 8, 2]
From there you can modify the resulting list as needed...
Upvotes: 0
Reputation: 12349
To just convert a string to a list of digits:
digits = [int(x) for x in mystr]
Lists are mutable, so you can modify individual digits this way.
Converting back to a string (assuming all your numbers are single-digit values):
''.join([str(x) for x in digits])
And you can use strides in slicing to deal with alternating digits
digits[::2]
digits[1::2]
Upvotes: 0
Reputation: 19057
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.
Upvotes: 4