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

4

u/Insomnia_Calls 1d ago edited 1d ago

Your solution is good. Just a few notes:

  1. The quotation marks simply show that the variable is a string. So, at the beginning of your code, you don’t have input_string= 12 33, you have input_string =‘12 33’. The first one would through an error, the second is a legitimate string of characters.

  2. When splitting a string with .split(), the result is a list of strings, hence the quotation marks around the items in the list.

  3. Yes, you have to explicitly tell Python that you would like to turn a string into an integer.

Edit: changed wording in 3.

1

u/ZimranYaison86 1d ago

do you think the course has them using input() right before this and thats why they didnt realize it started as a string?

1

u/Insomnia_Calls 19h ago

Not sure, question for OP.
If I were to make the problem, I would definitely make it so they use input(). But I would also not have the students separate a list into two lists, it is not very udeful or instructive, IMO.