So, what is a string? A string is a sequence of zero or more characters. Strings can be enclosed in double quote (
") or single quote (
') characters, and if you need to include either of those in a string, it’s possible to do that as strings can also take the format of raw or triple-quoted strings, both of which you’re going to see later in this section.
00:44 And as you can see, both have the same representation when printed by Python. Choosing which to enclose the string in can be important because sometimes you’ll want to have one or the other inside a string. So here you can see a string is being defined using double quotes, and it has a single quote inside it, which Python is untroubled by.
It’s happy to print that out. But if that was done using single quotes throughout, bpython is already giving us a colored hint that this isn’t right, and we have a
SyntaxError because we have the beginning of the string which is defined up to
'I wasn', and then the rest of the line doesn’t make sense to Python.
01:33 So that is not the way that you do that. Now clearly, you can do it the other way around. You could have a single-quoted string which has double quotes inside, and that will work perfectly well.
01:58 Python has got confused about this. We know that that should be the whole string, all the way there, but that’s not the way that Python sees this. Sometimes there’ll be examples when you need to use single and double quotes inside a string, and you’re going to see how to do that a little bit later.
As you would expect from the other videos you’ve already seen, if we use
type() on one of the strings we’ve defined, we can see it’s of the
str string class, and this can be used to convert other data types into strings.
Become a Member to join the conversation.