0

I am trying to convert the string str1 to a list of numbers so that I could sum them up. First I use the split() function to make sense of the numbers in str1, I cast the string into a list (lista) and after that I use the map() function in order to convert the strings in the new list to integers:

   str1="13,22,32,4,5"

   str2=str1.split()
   lista=list(str2)

   lista=map(int,lista)

   print sum(lista)

For some reason I get the following error message: "ValueError: invalid literal for int() with base 10: '13,22,32,4,5'"

1 Answer 1

2

Using split() will not split up str1, as without the sep argument the default separator is a space ' '. Hence:

str2 == ["13,22,32,4,5"]

you need to specify that split should use a comma ','. In fact, you can combine your operations into one:

sum(map(int, str1.split(',')))
Sign up to request clarification or add additional context in comments.

2 Comments

I see what you did there. I managed to make mine work only by adding (",") to the split function parentheses. Thank you!
You don't need to call lista = list(str2); split returns a list, so you can use lista = str1.split(',')

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.