r/learnpython • • 11m ago

String split and single quotation marks

I'm currently doing the Finnish Python MOOC, and at the end of chapter 4 you're not quite introduced to the split function. The problem is simple: your input a is string containing two integers, and this string must be split into two different lists, repeating for every new input string. However, the lists contain every integer within single quotation marks, which makes them unusable for mathematical operations. Am I supposed to just add another line to convert the lists into something useful? Seems really convoluted.

(And, if someone would be so kind, why does Python do this thing with the quotation marks?)

#In short, I have this:
input_string = 12 33
input_string.split()
list_a = ['12']
list_b = ['33']

#While I need this:
list_a = [12]
list_b = [33]

#So I do this:
a_no_quotes = []
for item in list_a:
    a_no_quotes.append(int(item))
1 Upvotes

2 comments sorted by

•

u/danielroseman 3m ago

You can use a list comprehension.

a_no_quotes = [int(item) for item in list_a]

Note, the problem is not the "single quotation marks", it is that splitting a string still gives you a string, but you want integers.

•

u/00HoppingGrass00 0m ago

That's not quite how split works. Split returns one list containing all of the substrings, so splitting "12 33" gives you ["12", "33"] rather than two lists.

Also it makes sense that splitting a string will give you strings, no? Python won't magically know that the substrings can be converted to integers.