Text Outputs
- 03:21
Learn how to incorporate text into your code output in Python.
Downloads
No associated resources to download.
Transcript
Now we're going to talk about incorporating text into your code output. And it's very simple to do, just use the print function and then in either single quotes or double quotes, include the text that you want to be in your output. So, real quick, I'm going to remove these single quotes, and if I execute this code cell, what do you think is going to happen? So Python is going to read print, and then when it gets to the word, please, it's not going to know that that's text and it's going to try and execute it as if it were Python code. So please wait while the application loads is not correct, Python syntax. So if I hold shift and press enter, it's going to give me an invalid syntax error, which is what we would expect if I go back and I add those single quotes. Now, when I execute it, it gives me the text that I wanna print and exactly the same, if I use double quotes, I'm going to get the same exact output. And I just do this to show you that you can use whichever one you want. All I've done is I've swapped these single quotes for double quotes on each side, and when I execute that, I'm gonna get exactly the same output. The difference is if I wanted to create a cell and I wanted to show you the difference between its possessive and it's with an apostrophe, it is. So now that presents a problem if I'm using single quotes because if I open my text with a single quotation, now my code says, okay, open quote, it's, and it, and then that single quote ends my text. So now I have this hanging s and if I try to execute that, that's also invalid syntax. So I get an error if I want to correct it. Instead, since I'm using this single quote within my text, I can open with a double quote and now Python knows, okay, we're opening with a double quote. So when I get to this single quote, it's, it is, I know that that's not the end of my text, so I'm gonna keep going until I see a double quote close that text. So if I hit shift and enter, I get it's, and it's with the apostrophe. Alternatively, let's say that I really wanted to use a single quote like this and my text is ending at this apostrophe.
How can I fix that? Well, what I can do is I use the backslash and what the backslash does, and note that this is not a regular forward slash that you would use. This is a backslash, which is probably above your enter button. The backslash tells Python that the character proceeding is going to be a literal character. What that means is don't interpret it as you normally would in Python code, use the secondary operation, which is using this as a normal apostrophe and not to end this block of text. So this backslash tells Python that this is a literal apostrophe not to close the text block. So now when I put a single quote here, it ends my text block and it prints exactly the same as if I had used double quotes on the outside.