解释器就像一个简单的计算器: 你可以在它上面输入一个表达式,它就会写值。表达式语法很简单:操作符+ 、-、* 和/的工作原理和大多数其他语言(例如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
可以使用**运算符来计算幂
>>> 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 "" , line 1, in <module>
NameError: name 'n' is not defined
完全支持浮点;带有混合类型操作数的操作符将整型操作数转换为浮点数:
>>> 4 * 3.75 - 1
14.0
在交互模式下,最后打印的表达式被赋值给变量_。这意味着当你使用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还内置了对复数的支持,并使用i或j后缀来表示虚数部分(例如3+5j)。
除了数字,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 "" , line 1
prefix 'thon'
^^^^^^
SyntaxError: invalid syntax
>>>('un' * 3) 'ium'
File "" , line 1
('un' * 3) 'ium'
^^^^^
SyntaxError: invalid syntax
如果你想连接变量,或者一个变量和一个字面量,使用+:
>>>prefix + 'thon'
'Python'
字符串可以被索引(下标),第一个字符的索引为0。没有单独的字符类型;字符就是长度为1的字符串:
>>>word = 'Python'
>>>>>>word[0] # character in position 0
'P'
>>>word[5] # character in position 5
'n'
index也可以是负数,从右边开始计数:
>>>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
切片索引有有用的默认值;省略的第一个索引默认为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'
注意如何总是包含开始,而总是排除结束。这确保s[:i] + s[i:]总是等于s:
>>>word[:2] + word[2:]
'Python'
>>>word[:4] + word[4:]
'Python'
记住切片如何工作的一种方法是将索引看作是指向字符之间的,第一个字符的左边缘编号为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的边之间的所有字符组成。对于非负指标,如果两个指标都在范围内,则切片的长度是指标的差。例如,单词[1:3]的长度是2。
尝试使用过大的索引会导致错误:
>>>word[42] # the word only has 6 characters
Traceback (most recent call last):
File "" , line 1, in <module>
IndexError: string index out of range
然而,超出范围的切片索引在用于切片时被优雅地处理:
>>>word[4:42]
'on'
>>>word[42:]
''
Python字符串不能被改变——它们是不可变的。因此,对字符串中的索引位置赋值会导致错误:
>>>word[0] = 'J'
Traceback (most recent call last):
File "" , line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>word[2:] = 'py'
Traceback (most recent call last):
File "" , line 1, in <module>
TypeError: 'str' object does not support item assignment
如果你需要一个不同的字符串,你应该创建一个新的字符串:
>>>'J' + word[1:]
'Jython'
>>>word[:2] + 'py'
'Pypy'
内置函数len()返回字符串的长度:
>>>s = 'supercalifragilisticexpialidocious'
>>>len(s)
34
字符串是序列类型的例子,并支持这些类型所支持的常见操作。
字符串支持大量用于基本转换和搜索的方法。
具有内嵌表达式的字符串字面值。
关于使用str.format()格式化字符串的信息
printf-style String Formatting
当字符串是%操作符的左操作数时调用的旧格式化操作。
Python知道许多复合数据类型,用于将其他值组合在一起。最通用的是列表,它可以写成方括号之间用逗号分隔的值(项)的列表。列表可能包含不同类型的项,但通常所有项都具有相同的类型。
>>>squares = [1, 4, 9, 16, 25]
>>>squares
[1, 4, 9, 16, 25]
像字符串(和所有其他内置序列类型)一样,列表可以被索引和切片:
>>>squares[0] # indexing returns the item
1
>>>squares[-1]
25
>>>squares[-3:] # slicing returns a new list
[9, 16, 25]
所有的片操作都返回一个包含所请求元素的新列表。这意味着下面的切片返回列表的浅拷贝:
>>>squares[:]
[1, 4, 9, 16, 25]
列表还支持像拼接这样的操作:
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
与不可变的字符串不同,列表是一种可变类型,即可以更改其内容:
>>>cubes = [1, 8, 27, 65, 125] # something's wrong here
>>>4 ** 3 # the cube of 4 is 64, not 65!
64
>>>cubes[3] = 64 # replace the wrong value
>>>cubes
[1, 8, 27, 64, 125]
你也可以通过使用append()方法在列表的末尾添加新项(我们将在后面看到更多关于方法的内容):
>>>cubes.append(216) # add the cube of 6
>>>cubes.append(7 ** 3) # and the cube of 7
>>>cubes
[1, 8, 27, 64, 125, 216, 343]
也可以给切片赋值,这甚至可以改变列表的大小或完全清除它:
>>>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>>letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
# replace some values
>>>letters[2:5] = ['C', 'D', 'E']
>>>letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
# now remove them
>>>letters[2:5] = []
>>>letters
['a', 'b', 'f', 'g']
# clear the list by replacing all the elements with an empty list
>>>letters[:] = []
>>>letters
[]
内置函数len()也适用于列表:
>>>letters = ['a', 'b', 'c', 'd']
>>>len(letters)
4
可以嵌套列表(创建包含其他列表的列表),例如:
>>>a = ['a', 'b', 'c']
>>>n = [1, 2, 3]
>>>x = [a, n]
>>>x
[['a', 'b', 'c'], [1, 2, 3]]
>>>x[0]
['a', 'b', 'c']
>>>x[0][1]
'b'