Python学习手册——类型与运算(字符串与列表)

Python是动态类型的(它能自动地跟踪你的类型而不是要求声明代码),但是它也是强类型语言(你只能对一个对象进行适合该类型的有效的操作)。
在python中的每一个对象都可以分为不可变性或者可变性。在核心类型中,数字、字符串和元组是不可变性;列表和字典可以完全自由地改变。这种不变性可以用来保证在程序中保持一个对象固定不变。

字符串

>>> S = 'Spam'
>>> S
'Spam'
>>> S.find('pa')
1
>>> S
'Spam'
>>> S.replace('pa','XYZ')
'SXYZm'
>>> S
'Spam'
>>> S='Spam'
>>> S.upper()
'SPAM'
>>> S.isalpha()
True
>>> line = 'aaa,bb,cccccc,dd'
>>> line.split(',')
['aaa', 'bb', 'cccccc', 'dd']
>>> line
'aaa,bb,cccccc,dd'
>>> line = 'aaa,bb,cccccc,dd\n'
>>> line = line.rstrip()
>>> line
'aaa,bb,cccccc,dd'
# 格式化的高级替代操作
>>> '%s,eggs,and %s'%('spam','SPAM!')
'spam,eggs,and SPAM!'
>>> '{0},eggs,and {1}'.format('spam','SPAM!')
'spam,eggs,and SPAM!'
# 查询属性
dir(S)
# 查询属性的用处
help(S.属性名)
模式匹配(略)

列表

>>> # 嵌套
>>> M = [[1,2,3],
...     [4,5,6],
...     [7,8,9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> M[0]
[1, 2, 3]
>>> M[0][2]
3

>>> # 列表解析
... col2 = [row[1] for row in M]
>>> col2
[2, 5, 8]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [row[1]+1 for row in M]
[3, 6, 9]
>>> [row[1]+1 for row in M if row[1]%2 == 0]
[3, 9]
>>> diag = [M[i][i] for i in [0,1,2]]
>>> diag
[1, 5, 9]
>>> doubles = [c*2 for c in 'spam']
>>> doubles
['ss', 'pp', 'aa', 'mm']
>>> G = (sum(row) for row in M)
>>> next(G)
6
>>> next(G)
15
>>> list(map(sum,M))
[6, 15, 24]
>>> {sum(row) for row in M}
{24, 6, 15}
>>> {i:sum(M[i]) for i in range(3)}
{0: 6, 1: 15, 2: 24}
>>> [ord(x) for x in 'spaam']
[115, 112, 97, 97, 109]
>>> {ord(x) for x in 'spaam'}
{112, 97, 115, 109}
>>> {x:ord(x) for x in 'spaam'}
{'s': 115, 'p': 112, 'a': 97, 'm': 109}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值