r/learnpython • • 23h 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

2

u/00HoppingGrass00 23h 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.

0

u/up-with-miniskirts 23h ago

As I said, I need two separate lists, and I left out the "make two lists" part.

So, the quotation marks exist to make sure that no substring ends up as functioning code that might throw off the program?

5

u/00HoppingGrass00 23h ago edited 22h ago

Those quotation marks just mean that the list items are strings.

As to why they stay as strings... Well, Python can't read your mind. It doesn't know whether you want them to stay as strings, or converted to integers, or converted to floats, or whether they can be converted at all. Also design-wise, one function/method should only do its duty and nothing more. If you want to convert, you have to explicitly call the int function. That's not within the scope of the split method.

0

u/up-with-miniskirts 22h ago

I think I got thrown off a bit by split() returning strings in single quotes, while the course material always uses double quotes (though it's mentioned that they're interchangeable).

3

u/MezzoScettico 21h ago

Neither of those is part of the string. It's just the way the string is displayed to YOU, so you understand it's a string, or the way you tell Python that an object is a string. As far as I know, both single or double quotation marks are legitimate for this purpose and completely interchangeable.

Even the Style Guide doesn't make a recommendation either way. It's up to you (or the leads if you're working on a team).

0

u/up-with-miniskirts 20h ago

The course material tends to be rather Spartan. Many features of the code are barely explained, with some even just showing up in model solutions without further information. In this case, the course said to use the split function, literally followed by "just google it."

My confusion between strings and ints arises from this. A number is an int when it's not in quotation marks, and a string when it is. Thus, my_string = 1 is an int, while my_string = "1" is a string. Logically, my_string = 1 2 should be an int, or a pair of ints, or some other int thing, and when you split it, it should return ints, not strings. But that's not how it is.

1

u/MezzoScettico 20h ago edited 20h ago

my_string = 1 2 should be interpreted as invalid, and indeed when I type it into my Python interpreter I get a syntax error. Does your Python actually accept your code?

my_string = (1, 2) would be interpreted as a tuple of ints.

my_string = [1, 2] would be interpreted as a list of ints.

Neither type of object has a split method, so the "if you split it" question is not meaningful.

1

u/up-with-miniskirts 19h ago

Yeah, you're right. I've messed up user input and hard-coded integers here.

The actual code looks like this (I think it works as is, but it's not important):

results = input("Exam points and exercises completed: ") #input consists of two numbers
exam_list = []
exercise_list = []
temp_list = results.split()
exam_list.append(temp_list[0])
exercise_list.append(temp_list[1])

exam_list_int = []
for item in exam_list:
    exam_list_int.append(int(item))

So, you start with two numbers, which are integers, but in the mathematical sense only. You actually have a string of two numbers, which needs to be split into into its substrings, into two different lists. Both lists of substrings then need to be converted into lists of integers. Split has not been explained, and neither has been how to convert a list of strings into a list of integers.

And then I try to get my half-baked code to work, and I only end up understanding even less.

1

u/MezzoScettico 16h ago

I'm confused about the "two lists" thing. If you have only two numbers total, where are the lists coming from?

Could you show an example of typical input and what the output would look like if you did this with pencil and paper?

1

u/up-with-miniskirts 16h ago

The results = input("") line is supposed to be run until halted by the user. Things were difficult enough as they were, so I left that out.

I hope I can leave the whole int vs. string problem behind me now, though. It's far from the first time I've banged my head against it.

1

u/NSNick 11h ago

In the future, before googling it may I recommend looking it up in the documentation?

4

u/Insomnia_Calls 23h ago edited 22h 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 16h 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 10h 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.

2

u/desrtfx but other languages pro 20h ago

Please, tell us the exact exercise.

1

u/POGtastic itertools evangelist 20h 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.

0

u/Brian 19h ago

However, the lists contain every integer within single quotation marks

This is kind of a common issue with learners, where I think there's a bit of a conceptual leap you need to make. Specifically, don't mix up the representation of a thing with the thing itself.

Ie. a string, an integer, a class and so on are objects sitting there in memory, represented some way by bytes in RAM. Think of these as the objects themselves.

However, we can't see inside computer memory - we can display text with print, but some of those things aren't text, but we still need to display them. So what we do is create a representation of the object in text and show that. Eg. we have an integer object forty-two sitting in memory somewhere as a binary representation of the number, but when we want to print that number, we actually need to do a bit of work to convert it to a string in a familiar decimal form. So there's a bit of code that does this - it's what gets run when you call str(my_variable) (and print behind the scenes will be making this call). What it does depends on the type, and so each object has special hooks that say "How should this be represented", and for integers this code looks at the memory, and builds up a string by converting the number to decimal, finding the correct character code to represent each digit, and returns it.

These hooks are actually available to your own code, where you can override "How should this object be displayed". Eg:

class MySpecialObject:
    def __str__(self):
        return "This is the string I return to say how I should be displayed"

obj = MySpecialObject()
print(obj)  # Prints:  This is the string I return to say how I should be displayed

There's also a similar special function called __repr__, invoked by the repr(obj) function which is similar, but there more for a "programmer friendly" representation - it's what gets called when it's displaying it at the python >>> prompt. Ie. the integer 42 and the string "42" are very different objects, but they display the same:calling str() on them gives you the same string. But __repr__ displays them in a less ambiguous way, by adding quotes aroung the string, but leaving the integer unquoted (ie. "42" vs 42)

And this is fundamental to what you're doing. Ie. it's not that:

lists contain every integer within single quotation marks, which makes them unusable for mathematical operations.

It's more that your list is a list of strings - the quotation marks aren't part of them, that's just how python is displaying them, because a list displaying its contents uses the __repr__ of its elements, and those elements are strings whose __repr__ displays with quotes.

So a better way of thinking about this is "I have a list of strings, which I can't do maths on, because I need a list of integers instead". Hence the solution is "Convert the strings to integers", which you can do with the int() function. Eg:

int_list = [int(x) for x in string_list]

0

u/VadumSemantics 15h ago

I will encourage you to try some simpler expressions.

Adding print() to your code is an easy way to see what it is doing. Once you see what the types & values are you can comment out the print.

I'll going to introduce the type() function, which may seem like a bit of a cheat.

But knowing the type of some value can be super useful.

example code

a = 123
print("type(a)=", type(a), "  a=", a)
b = 123.456
print("type(b)=", type(b), "  b=", b)
c = '123'
print("type(c)=", type(c), "  c=", c)
d = int(c)
print("type(d)=", type(d), "  d=", d)

output

type(a)= <class 'int'>   a= 123
type(b)= <class 'float'>   b= 123.456
type(c)= <class 'str'>   c= 123
type(d)= <class 'int'>   d= 123

edit: fixed copy/paste fail on output.

-1

u/danielroseman 23h 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 23h 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 23h 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).

-1

u/woooee 21h ago
#While I need this:
list_a = [12]
list_b = [33]

There is no reason to do this as there is no reason to create a list that contains one string. Just use the original string.

for item in list_a:
    a_no_quotes.append(int(item))

can just be

a_no_quotes.append(the_string)

Note that if you want to split a number, use divmod and divide by one

whole, remainder = divmod(12.33, 1)  ## returns floats