What’s a String and What’s Knot? 

On how strings work in Python

Strings are the things stuck between quotation marks.  It’s like dialogue in a book, except a bit knottier.  So, “Hello, it’s me” is a string. Using IDLE (see previous post), try printing that out in Python 3 like this:

>>>print (“Hello, it’s me”)

It should work like a charm. Now, try this:

>>>print (Hello, its me)

This time, I’ve set you up for failure. You should have gotten the annoying message: SyntaxError: invalid syntax. That’s because Python is looking for a string here and won’t accept it without some quotation marks. It’s like having a super strict elementary school teacher who will not cut you any slack (yes, I’m looking at you, Mrs. Decker!). But Python will also accept some other versions of quotations marks to make a string. Try these two versions in your Shell:

                                                >>>print ('Hello, it is I')
                                               >>>print ('''Hello, it is I''')

Those should work. Bottom line: you can use single, double, or even triple quotation marks to make a string. (Mrs. Decker would have hated that.) Now, try this:

                                                >>>print ('Hello, it's me')

That should give you another error, this time a “SyntaxError.” That’s because Python can’t tell the difference between a quotation mark and an apostrophe. In its little literal mind, it sees three quotation marks and so can’t tell where the string is starting and ending. So, it’s not quite a string. It’s more of a knot. And knots will tangle you up. Kind of like a real python will. Beware.

Indian Rock Python Python molurus. Photographed by Dr. Raju Kasambe at Keoladeo National Park, Bharatpur, Rajasthan. Wikimedia Commons.

PS – There are about a bajillion ways of messing around with strings. For a long list of ways of playing with string, I recommend you have a look at the official list of string methods. Just don’t let the list intimidate you. For most folks, only a handful of these are used on a day-to-day basis.