Learn Python The Hard Way(10)

原创
2015/04/14 19:23
阅读数 29

    This use of the \ (back-slash) character is a way we can put difficult-to-type characters into a string. There are plenty of these "escape sequences" available for different characters you might want to put in, but there's a special one, the double back-slash which is just two of them \\. These two characters will print just one back-slash. We'll try a few of these sequences so you can see what I mean.

    Another important escape sequence is to escape a single-quote ' or double-quote ". Imagine you have a string that uses double-quotes and you want to put a double-quote in for the output. If you do this "I "understand" joe." then Python will get confused since it will think the " around "understand" actually ends the string. You need a way to tell Python that the " inside the string isn't a real double-quote. To solve this problem you escape double-quotes and single-quites so Python knows to include in the string. 

    The second way is by using triple-quotes, which is just """ and works like a string, but does you also can put as many lines of text you as want until you type """ again. We'll also play with these.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat

运行结果:

                       




展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部