Python 数据类型

查看全部 Python3 基础教程

数值

解释器的行为就像一个计算器。你可以向它输入一个表达式,它会返回结果。表达式的语法简明易懂:+,-,*,/ 和大多数语言中的用法一样,比如 C 或 Pascal,括号用于分组。

加减乘除

等号 = 用于给变量赋值,同一个值可以同时赋给几个变量。

>>> x = y = z = 0  # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6

除法运算 / 只返回 float 类型,可以使用 // 向下取整;取余运算使用 %

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

Python 完全支持浮点数,不同类型的操作数混在一起时,操作符会把整型转化为浮点数。

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

幂运算

幂运算可以使用 **

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

复数

Python 也同样支持复数,虚部由一个后缀 j 或者 J 来表示。带有非零实部的复数记为 (real+imagj),或者可以通过 complex(real, img) 函数创建。

>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)

复数总是由实部和虚部两部分浮点数来表示。可以从 z.realz.imag 得到复数 z 的实部和虚部。

>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5

无法将复数转化为实数,用于向浮点数和整型转化的函数 float(), int()long() 不能用于复数。可以使用 abs(z) 取得它的模,也可以通过z.real 得到它的实部。

>>> a=3.0+4.0j
>>> float(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
>>> a.real
3.0
>>> a.imag
4.0
>>> abs(a)  # sqrt(a.real**2 + a.imag**2)
5.0
>>>

_ 变量

交互模式下,最近一次表达式输出保存在 _ 变量中。这意味着把 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'
>>> '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() 函数中输出字符串对引号和转义符号 \ 的处理是不同的,通常 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.

如果不想字符串中的 \ 后跟的字符被当作特殊字符,可以使用 raw strings,在引号前加一个 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

字符串可以跨越多行,一种方式是用三引号 """..."""'''...''',行尾 \n 会被自动包括进来,可以通过在行尾加 \ 阻止该行为。

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

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

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

字符串的连接

字符串可以用 + 连接起来,可以用 * 进行重复。

>>> # 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 的切片由这两个标志之间的字符组成。

对于非负索引,切片长度就是两索引的差(如果两索引都在范围内)。例如,word[1:3] 的长度是 2。

引用超出范围的索引会产生错误。

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

但是,引用超出范围的切片处理方式却很优美,过大的索引代替为字符串大小,下界比上界大的返回空字符串。

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

Python 字符串不能改写,按字符串索引赋值会产生错误。

>>> word[0] = 'J'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

然而,可以通过简单的组合方式生成新的字符串。

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

字符串参考资料

Text Sequence Type — str
Strings are examples of sequence types, and support the common operations supported by such types.

String Methods
Strings support a large number of methods for basic transformations and searching.

Formatted string literals
String literals that have embedded expressions.

Format String Syntax
Information about string formatting with str.format().

printf-style String Formatting
The old formatting operations invoked when strings are the left operand of the % operator are described in more detail here.

列表

Python 中最通用的复合数据类型是列表,用于把相同类型的元素组织到一起。

列表的表示

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

列表支持嵌套。

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

内置函数 len() 同样适用列表。

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

列表的连接

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

列表的索引和切片

类似字符串和其他内置的序列类型,列表也可以被索引和切片。

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

列表的修改

与字符串不同,列表是可变类型,其内容可以被改变。

>>> 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
[]




参考资料

Python3 Tutorial – An Informal Introduction to Python

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值