MrJonesIsCountingCrows
MrJonesIsCountingCrows

Reputation: 155

Converting only one column into int from string

I have a list of lists. For example a sample_list

[['11', 'A', '23.45'], [['15', 'B', '11.63'], ['53', 'C', '62.78']]

I want to convert only the third column into the int. so the output looks something like:

[['11', 'A', 23.45], [['15', 'B', 11.63], ['53', 'C', 62.78]]

I tried doing a bunch of things including:

for item in sample_list:
    item[2] = int(item[2])

But no matter what I do, I keep getting an error:

invalid literal for int() with base 10: '23.45'

Not sure what I am doing wrong but i am not allowed to use any libraries like pandas or anything.

Upvotes: 2

Views: 41

Answers (1)

Selcuk
Selcuk

Reputation: 59425

That's because 23.45 is not an integer. Try

item[2] = int(float(item[2]))

This will first convert the string to a float, then float to an int.

Upvotes: 2

Related Questions