What Is a String? (Solution)
00:00 Here I am in the interactive IDLE shell. I’ll go ahead and take quick notes of the different tasks that I’ve got to do here. There were four tasks. I always like to start with just taking notes on what I’m supposed to do, which helps me get organized and remember what the task is actually.
00:51 So I just took some short notes to remind myself of the tasks and I’m going to get going. The first one is to print double quotes in the string, and I can do that using single quotation marks to delimit the string.
01:29 I’m using single quotation marks to delimit the string, and then the double quotation marks inside. They’re not considered as string delimiters, but they’re just the characters double quotation marks.
print() call. And now I will use double quotation marks to delimit the string. So I’m opening it up with a double quotation mark. Then I can write something. I will say,
got an apostrophe", and I use an apostrophe after the word string.
02:11 So this string has got an apostrophe. This is not an English lesson, and I wouldn’t be the best person to teach this anyway. But I do have a single quotation mark or an apostrophe in the string, and I can now press Enter, and this will execute and work fine.
Exercise three was to write a multiline string that also prints on multiple lines. So this I can do by using triple quotation marks. So for example, triple double quotation marks (
""") or triple single quotation marks (
''') works the same.
03:30 And then finally, the last task, write a multiline string that prints on a single line. And you can do that with escaping the newline character. Now I’m just going to use one double quotation mark.
And I’ll say,
"This one-line string was written and then I will use the backslash character (
\), which escapes. It’s a special character that escapes the following character, which in this case is going to be a newline because after putting the backslash character, I’ll press Enter and continue typing in the next line.
But Python considers this to still be part of the previous line. So continue writing my string saying,
using multiple lines" and then close the string. With a string like this one that’s delimited with only one quotation mark, spreading a string over multiple lines like I do here only works when you use the backslash character.
04:30 And now press Enter. And as you can see, it displays on just a single line because I escaped the newline character that I used in here. All right, so that was a quick recap on the different ways you can mix and match quotation marks when writing your string literals.
Become a Member to join the conversation.