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

25 comments sorted by

View all comments

1

u/POGtastic itertools evangelist 4d ago

It seems really convoluted to require you to explicitly convert strings to integers

Strings of text could be anything.

input_string = "foo bar" # uh oh, these aren't numbers!

We also have an addition operation for strings (concatenation). So yes, you need to call int to parse those strings into integers, which throws an exception if the conversion fails.

You will generally find that the more implicit a language is with things like type conversions, the harder it is to keep track of what is happening. Javascript programmers have an absolutely miserable time with this.


Specifically for mapping a function onto a list of elements, Python provides list comprehensions and the map builtin.