3.1.1. 数字
解释器像一个简单的计算器:输入表达式,就会给出答案。表达式的语法很直接:运算符 +、-、*、/ 的用法和其他大部分语言一样(比如,Pascal 或 C);括号 (()) 用来分组。例如:
>>>>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number
1.6
整数(如,2、4、20 )的类型是 int,带小数(如,5.0、1.6 )的类型是 float。本教程后半部分将介绍更多数字类型。
除法运算(/)返回浮点数。用 // 运算符执行 floor division 的结果是整数(忽略小数);计算余数用 %:
>>>>>> 17 / 3 # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3 # floor division discards the fractional part
5
>>> 17 % 3 # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2 # floored quotient * divisor + remainder
17
Python 用 ** 运算符计算乘方 :
>>>>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
等号(=)用于给变量赋值。赋值后,下一个交互提示符的位置不显示任何结果:
>>>>>> width = 20
>>> height = 5 * 9
>>> width * height
900
如果变量未定义(即,未赋值),使用该变量会提示错误:
>>>>>> n # try to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
Python 全面支持浮点数;混合类型运算数的运算会把整数转换为浮点数:
交互模式下,上次输出的表达式会赋给变量 _。把 Python 当作计算器时,用该变量实现下一步计算更简单,例如:
>>>>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
最好把该变量当作只读类型。不要为它显式赋值,否则会创建一个同名独立局部变量,该变量会用它的魔法行为屏蔽内置变量。
除了 int 和 float,Python 还支持其他数字类型,例如 Decimal 或 Fraction。Python 还内置支持 复数,后缀 j 或 J 用于表示虚数(例如 3+5j )。
3.1.2. 字符串
除了数字,Python 还可以操作字符串。字符串有多种表现形式,用单引号('……')或双引号("……")标注的结果相同 。反斜杠 \ 用于转义:
>>>>>> 'spam eggs' # single quotes
'spam eggs'
>>> 'doesn\'t' # use \' to escape the single quote...
"doesn't"
>>> "doesn't" # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
交互式解释器会为输出的字符串加注引号,特殊字符使用反斜杠转义。虽然,有时输出的字符串看起来与输入的字符串不一样(外加的引号可能会改变),但两个字符串是相同的。如果字符串中有单引号而没有双引号,该字符串外将加注双引号,反之,则加注单引号。print() 函数输出的内容更简洁易读,它会省略两边的引号,并输出转义后的特殊字符:
>>>>>> '"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.
如果不希望前置 \ 的字符转义成特殊字符,可以使用 原始字符串,在引号前添加 r 即可:
>>>>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
字符串字面值可以实现跨行连续输入。实现方式是用三引号:"""...""" 或 '''...''',字符串行尾会自动加上回车换行,如果不需要回车换行,在行尾添加 \ 即可。示例如下:
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
字符串可以用 + 合并(粘到一起),也可以用 * 重复:
>>>>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
相邻的两个或多个 字符串字面值 (引号标注的字符)会自动合并:
>>>>>> '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.'
这项功能只能用于两个字面值,不能用于变量或表达式:
>>>>>> prefix = 'Py'
>>> prefix 'thon' # can't concatenate a variable and a string literal
File "<stdin>", line 1
prefix 'thon'
^
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
File "<stdin>", line 1
('un' * 3) 'ium'
^
SyntaxError: invalid syntax
合并多个变量,或合并变量与字面值,要用 +:
>>>>>> prefix + 'thon'
'Python'
字符串支持 索引 (下标访问),第一个字符的索引是 0。单字符没有专用的类型,就是长度为一的字符串:
>>>>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
索引还支持负数,用负数索引时,从右边开始计数:
>>>>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'
注意,-0 和 0 一样,因此,负数索引从 -1 开始。
除了索引,字符串还支持 切片。索引可以提取单个字符,切片 则提取子字符串:
>>>>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
注意,输出结果包含切片开始,但不包含切片结束。因此,s[:i] + s[i:] 总是等于 s:
>>>>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
切片索引的默认值很有用;省略开始索引时,默认值为 0,省略结束索引时,默认为到字符串的结尾:
>>>>>> word[:2] # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:] # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to the end
'on'
还可以这样理解切片,索引指向的是字符 之间 ,第一个字符的左侧标为 0,最后一个字符的右侧标为 n ,n 是字符串长度。例如:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
第一行数字是字符串中索引 0...6 的位置,第二行数字是对应的负数索引位置。i 到 j 的切片由 i 和 j 之间所有对应的字符组成。
对于使用非负索引的切片,如果两个索引都不越界,切片长度就是起止索引之差。例如, word[1:3] 的长度是 2。
索引越界会报错:
>>>>>> word[42] # the word only has 6 characters
声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系
[邮箱地址] 删除