Python学习笔记之四——类型

类型

数字

  Python 解释器可作为一个简单的计算器:你可以向它输入一个表达式,它将返回其结果。表达式语法很直白: 运算符+、 -、 *和/的用法就和其它大部分语言一样;括号(())可以用来分组。例如:

>>> 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,带有小数部分数字(e.g. 5.0, 1.6)的类型是float。
除法(/)永远返回一个浮点数。如要使用floor 除法(向下取整)并且得到整数结果(丢掉任何小数部分),你可以使用//运算符;要计算余数你可以使用%:

>>> 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  # result * 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 "<stdin>", line 1, in <module> 
NameError: name 'n' is not defined 

整数和浮点数的混合计算中,整数会被转换为浮点数:

>>> 3 * 3.75 / 1.5 
7.5 
>>> 7.0 / 2 
3.5 

在交互模式下,最近一次表达式的值被赋给变量_。这意味着把Python 当做桌面计算器使用的时候,可以方便的进行连续计算,这里的变量_相当于是python 交互模式下的一个内置变量。
例如:

>>> tax = 12.5 / 100 
>>> price = 100.50 
>>> price * tax 
12.5625 
>>> price + _ 
113.0625 
>>> round(_, 2) 
113.06 

用户应该将这个变量视为只读的。不要试图去给它赋值 — — 你将会创建出一个独立的同名局部变量,并且屏蔽了内置变量。
除了int 和 float,Python还支持其它数字类型,例如小数 and 分数。Python还内建支持复数,使用后缀j 或 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," he said.' 
'"Yes," he said.' 
>>> "\"Yes,\" he said." 
'"Yes," he said.' 
>>> '"Isn\'t," she said.' 
'"Isn\'t," she said.' 

  在交互式解释器中,输出的字符串会用引号引起来,特殊字符会用反斜杠转义。虽然可能和输入看上去不太一样(括起来的引号可能会变),但是两个字符串是相等的。如果字符串中只有单引号而没有双引号,就用双引号引用,否则用单引号引用。print()函数生成可读性更好的输出, 它会省去引号并且打印出转义后的特殊字符:

>>> '"Isn\'t," she said.' 
'"Isn\'t," she said.' 
>>> print('"Isn\'t," she said.') 
"Isn't," she 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' 

然而这种方式只能用于两个字符串的连接,变量或者表达式是不行的。

>>> prefix = 'Py' 
>>> prefix 'thon'  # can't concatenate a variable and a string literal 
  ... 
SyntaxError: invalid syntax 
>>> ('un' * 3) 'ium' 
  ... 
  SyntaxError: invalid syntax 

如果你想连接多个变量或者连接一个变量和一个常量,使用+:

>>> prefix + 'thon' 
'Python' 

这个功能在你想切分很长的字符串的时候特别有用:

>>> text = ('Put several strings within parentheses ' 
            'to have them joined together.') 
>>> text 
'Put several strings within parentheses to have them joined together.'           

字符串可以索引,第一个字符串的索引值为0。Python 没有单独的字符类型,字符就是长度为 1 的字符串

>>> 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' 

切片的索引有非常有用的默认值,省略的第一个索引默认为零,省略的第二个索引默认为切片的字符串的长度大小。

>>> 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' 

对于非负索引,如果上下都在边界内,切片长度就是两个索引之差。例如:word[1:3] 的长度是2。
如果单取一个字符串中的一个字母,索引的值如果超出了字符串的实际长度-1,那么会报错:

>>> word[42]  # the word only has 6 characters 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
IndexError: string index out of range 

但是,如果是做切片,Python会对超出范围的切片索引优雅地处理:

>>> word[4:42] 
'on' 
>>> word[42:] 
'' 

Python 的字符串是不可变类型,因此,如果赋值给字符串索引的位置会导致错误:

>>> word[0] = 'J' 
  ... 
TypeError: 'str' object does not support item assignment 
>>> word[2:] = 'py' 
  ... 
TypeError: 'str' object does not support item assignment 

如果需要一个不同的字符串,就应该创建一个新的字符串:

>>> 'J' + word[1:] 
'Jython' 
>>> word[:2] + 'py' 
'Pypy' 

内置函数len() 返回字符串的长度:

>>> s = 'supercalifragilisticexpialidocious' 
>>> len(s) 
34

列表

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
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值