r/learnpython • • 1d 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))
7 Upvotes

24 comments sorted by

View all comments

-1

u/danielroseman 1d 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.

2

u/up-with-miniskirts 1d ago

This is great, but, to the best of my abilities, I have not seen it mentioned or used in this MOOC, so I'm not technically allowed to be aware of its existence. (Unless it showed up somewhere in a block of theory, never to be seen again thereafter.)

2

u/danielroseman 1d ago

Well in that case your solution is fine.

But you do need to understand that strings and integers are not interchangeable; Python is what's called "strongly typed" and a string will always be a string unless you specifically convert it into something else, as you're doing by calling int(item).