GnUfTw
GnUfTw

Reputation: 357

How can I convert the index of a string to an integer in python?

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?

Upvotes: 0

Views: 13632

Answers (1)

Andy
Andy

Reputation: 50540

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

Upvotes: 1

Related Questions