We saw above that you can use triple double quotes (or even triple single quotes if you want) to print your text exactly as it appears. You can also control how many lines (or not) your text will span. Below is some example code demonstrating this: #!/usr/local/bin/python print "This is how you turn multiple lines into one line:" print " " multiple = "Here is a whole bunch of text that will \ fit on one line \ when we are through" print multiple print "The following text will print on four lines: " print "Hello\nhow\nare\nyou?" print "We can also use parentheses to add several strings on separate lines into one:" three_strings = ("I like " " to eat" " pancakes") print three_strings print "Here is how we create a space between lines\n" print "By using an escape character" This results in: This is how you turn multiple lines into one line:
Here is a whole bunch of text that will fit on one line when we are through The following text will print on four lines: Hello how are you? We can also use parentheses to add several strings on separate lines into one: I like to eat pancakes Here is how we create a space between lines By using an escape character Escaping Escaping allows you to print characters that are normally reserved for other purposes. To Python, a double quote normally signifies either the start of a string or the end of a string. If you want to print the quote so it shows up, you can encase it in another quote as described above (the preferred method) or you can use an escape character, as shown below: #!/usr/local/bin/python print "Here is an example of the single quote escape:" print 'It\'s okay' print "If you tried it without the escape, it would have returned an error.\n" print "The same with the double quote escape: " print "He said, \"Hi there.\" " print " " print "And of course you met our friend the newline escape\n\n" print "Here is the tab escape \t\t\t I'm over here!\n" print "And here is how you escape the backslash\\" This prints out: Here is an example of the single quote escape: It's okay If you tried it without the escape, it would have returned an error. The same with the double quote escape: He said, "Hi there."
And of course you met our friend the newline escape
Here is the tab escape I'm over here! And here is how you escape the backslash\ Here is a table showing some of the Escape characters:
Getting Raw Sometimes you want to print text without having to worry about Python interpreting it as an escape code. This can happen if you type a path to a file on a server or your computer. You can use raw strings to accomplish this, by placing an r in front of the first quotation mark, like so: #!/usr/local/bin/python print r"C:python25text.py" This prints out: C:python25text.py
blog comments powered by Disqus |
|
|
|
|
|
|
|