0

Lets say I assign a string '123,456' to some variable x. Now, I want to turn this string into a list (named counter in the block below) such that it takes the form [1, 2, 3, ,, 4, 5, 6]. I have tried to assign the string indeces to a list using a while loop shown below but I continue to get an error saying "int object does not support item assignment". Position has an initial value of 0.

while position < len(x):
    if x[position] == ',':
        counter[position] = x[position]
    else:
        counter[position] = int(x[position])
        position += 1

It seems my problem is that I am trying to convert an index of a string (a character) to an integer. Is there a way to convert the index of a string to an integer? If not, how else could I approach this?

2
  • If position is a string, then you can use int(position) to convert position to an integer. Commented Sep 26, 2014 at 3:59
  • position is an integer. x[position] is a character if im not mistaken. and my error is being raised when i try to convert a character to an integer. Commented Sep 26, 2014 at 4:01

1 Answer 1

1

You can do this by putting your string into a list

>>> s = '123,456'
>>> list(s)
['1', '2', '3', ',', '4', '5', '6']

If you want to convert these to integers then (except for that comma) you can do something similar to this:

>>> out = []
>>> for x in list(s):
...     try:
...         out.append(int(x))
...     except ValueError:
...         out.append(x)
...
>>> out
[1, 2, 3, ',', 4, 5, 6]

The ValueError catches the invalid conversion of a , to an int

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

1 Comment

And then I can convert each element of the list into an integer correct?

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.