练习9&练习10--那是什么?
一 基本语法
1 创建多行字符串的两种方式:
- 第一种是在月份中间加 \n ,它可以实现换行。
- 第二种方法是用三个双引号,即 """ ,这样就能像字符串一样运行,而且你可以多输入几行,最后再以 """ 结尾即可。注意三个双引号之间不能有空格。
2 转义字符的概念:\ 这个字符可以把没法输入的字符转化成字符串。
- 转义单引号\'或者双引号\":让 python 知道得把它们包含在字符串里
3 常见的转义字符
转义符 | 功能 | 转义符 | 功能 |
\\
|
反斜杠
|
\r ASCII
|
回车符
|
\'
|
单引号
|
\t ASCII
|
水平制表符
|
\"
|
双引号
|
\uxxxx
|
值为 16 位十六进制值xxxx
的字符(Unicodeonly)
|
\a
|
响铃符
|
\Uxxxxxxxx
|
值为 32 位十六进制值xxxx
的字符(Unicodeonly)
|
\b
|
退格符
|
\v
|
垂直制表符
|
\f
|
进纸符
|
\ooo
|
值为八进制值ooo 的字符
|
\n
|
换行符
|
\xhh
|
值为十六进制数 hh 的字符
|
\N{name}
|
Unicode 数据库中的字符名,其中
name 就是它的名字(Unicodeonly)
|
二 一些问题
1 斜杠/和反斜杠\是不同的符号,有着不同的作用,不能混淆
2 三个单引号''' 和 三个双引号"""用哪个更好? 这完全基于风格。现在先用 ''' ,当你感觉用 """ 更好或者别人都用它的时候你可以用 """ 。
三 代码
1 练习9
# Here's some new strange stuff,remember type it exactly. days = "Mon Tue Wed Thu Fri Sat Sun" months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" print("Here are the days:",days) print("Here are the months:",months) print(""" There's something going on here. With the there double-quotes. We'll be able to type as much as we like. Even 4 lines if we want,or 5,or 6. """)
运行结果:
PS E:\3_work\4_python\2_code\02_LearnPythonTheHardWay> python ex9.py Here are the days: Mon Tue Wed Thu Fri Sat Sun Here are the months: Jan Feb Mar Apr May Jun Jul Aug There's something going on here. With the there double-quotes. We'll be able to type as much as we like. Even 4 lines if we want,or 5,or 6.
2 练习10
tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backlash_cat = "I'm \\ a \\ cat." fat_cat = """ I'll do a list: \t* Cat food \t* Fishes \t* Catnip\n\t* Grass """ print(tabby_cat) print(persian_cat) print(backlash_cat) print(fat_cat)
运行结果:
PS E:\3_work\4_python\2_code\02_LearnPythonTheHardWay> python ex10.py I'm tabbed in. I'm split on a line. I'm \ a \ cat. I'll do a list: * Cat food * Fishes * Catnip * Grass