2

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.

7
  • 1
    Elaborate? An sample input and desired output would be a start. Commented Oct 26, 2011 at 18:10
  • The question is vague, shows zero research effort, and asks the respondents to do 100% of the work instead of providing relevant pointers. Commented Oct 26, 2011 at 18:17
  • Basically I need to be able to break down a string such as is_legal("1003998484") into a list comprising the digits of this number e.g. L = [1,0,0,3,9,9,8,4,8,4] so I can then use a stride and index to perform operations on every other digit e.g. add 3 to every second digit, then I need to be able to sum all of the digits I have returned. Commented Oct 26, 2011 at 18:20
  • R.E. Raymond Hettinger, I don't need the entire code I was just wondering if there was some sort of inbuilt function that would convert an integer into a list of it's digits, I'm sorry if I cam across as ignorant but I am new at this and do not know where to start. Commented Oct 26, 2011 at 18:22
  • 1
    @George Burrows: there is no problem with asking simple questions. I've posted the link for your benefit. If you don't read the tutorial (or skim through it at least to know what is there) you'll be stuck on trivial things constantly such as not knowing that a string is a sequence in Python. Commented Oct 26, 2011 at 20:17

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you very much, I did not know you could refer to items in something such as mystr in the same way you referred to items in a List, thanks for the basic explanation also. :)
you could drop [] inside sum() (use genexpr instead of listcomp).
Also is it possible to use the same start, stop, stride format in this instance? or is that reserved for lists? I.e. if I wanted to print the alternating digits from the end of an integer list1 = 0123456789, I could do print list1[-1::2] to return 8, 6, 4, 2, 0?
@GeorgeBurrows - lists, tuples, and strings are all sequences. The elements of a string sequence are strings of one character each. This is great when you want to pick characters out of a string, and confusing as heck when you accidentally pass a string to a function that expects a list.
0123456789 without quotes is an integer, not a string, and the leading zero makes it octal, not decimal, so that's a problem. And your start-stop-stride numbers are wrong, but '0123456789'[-2::-2] is '86420'. Try starting a python shell (just type python at the command line) and experiment yourself.
|
0

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]

3 Comments

This may be because I am new at this but to refer to mystr in such a manner would you have to explicitly put mystr = '47833893949' or could you refer to the string as mystr if it was defined as mystr('47833893949')? Thanks for the help :)
This assumes that mystr is the string representation of a number. If you have an integer, str(mynumber) will give you the string representation. I don't know what you mean by "if it was defined as mystr('47833893949')"; that's not a variable definition, that's a function call.
I have to define a function to check if a string input meets certain criteria, and the function has to be defined as: is_true(n) where n is the string, I need to change n into an integer, which from what I can gather would involve using for example integer = int(n) and I would have to type out n again, when the function should be able to have the number inputted just once and then it should be able to perform all the operations on n without needing any extra input. So ideally I would type n in the first time, and then it would give me an answer back of true or false if n meets these criteria.
0

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...

4 Comments

How would you suggest applying this if I have the input in this format?: test_num('482898477382') ? As now I cannot simply refer to the string without typing the string in again and putting something along the lines of input = '482898477382'?
If your input is a string you can omit the str() call and truncate it to [int(y) for y in x]. I'll update my answer with an example.
Sorry I phrased my question a bit awkwardly, if defined the string as test('12345') could I then refer to the string '12345' simply as test? So then to turn the string '12345' into an integer I could simply put integer = int(test)?
test('12345') would try to call the function test() with the parameter '12345'. To create a variable you'd do test = '12345' then, yes, you could do asInt = int(test)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.