以前经常想找时间阅读Python官方文档,但是一直拖延,这次想着要不直播读文档,让形式感推着我,被人看着读文档总不能偷懒了吧。第一天就发现还真是有一些Python入门书里没有提到的,或者那些你以为你懂了但是你并没有完全懂的知识。在这里就把这些内容记录下来。
_
。这意味着当你把Python用作桌面计算器时,继续计算会相对简单,比如:>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
在字符串中使用单引号和双引号效果是一样的,输出时的字符串是带着输入时的引号的
>>> 'spam eggs' # single quotes
'spam eggs'
如果字符串内用单引号,如it’s这种简写形式,那么可以用双引号里面用单引号,或者使用反斜杠转译单引号
>>> 'doesn\'t' # use \' to escape the single quote...
"doesn't"
>>> "doesn't" # ...or use double quotes instead
"doesn't"
这个一般入门书里都有说到,如果使用print函数会把外面的引号给去掉
>>> print("doesn't")
doesn't
下面是需要注意的:
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.' # \n means newline
>>> s # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s) # with print(), \n produces a new line
First line.
Second line.
第一个在单引号内嵌套一个双引号,双引号中的转译直接输出没效果,在print函数内生效。第二个即便是在单层引号内,\n这种直接输出也是没效果的,必须用print打印才生效。
字符串字面值可以跨行连续输入。一种方式是用三重引号:"""..."""
或 '''...'''
。字符串中的回车换行会自动包含到字符串中,如果不想包含,在行尾添加一个 \
即可。如下例:
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
将产生如下输出(注意最开始的换行没有包括进来):
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
如果没用行尾部的’’,输出内容前后有一个空行。
>>> 'Py' 'thon'
'Python'
我开始好奇这有什么用,不过把很长的字符串拆开分别输入时可以用到,但是现在都用反斜杠换行,其实这个确实没啥用。
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
虽然感觉没啥用,但却是让我对字符串换行多了点认识,我以为字符串嘛,和三引号差不多直接换行就行了,结果发现不行,必须在后面加上反斜杠才可以省略掉第一行末尾和第二行开头的引号。
在字符串中,如果通过索引查询时,索引超过字符串索引最大值会报错,但是在使用切片时,如果超过最大值会自动处理为字符串索引最大值
>>> word = 'Python'
>>> word[42] # the word only has 6 characters
Traceback (most recent call last):
File "", line 1, in
IndexError: string index out of range
>>> word[4:42]
'on'
>>> word[42:]
''
前面单独使用查询时报错,在使用切片时就没报错了。