Python Cookbook 1.1 处理字符串中的字符

问题:
要一个一个的处理字符串中的字符。

解决方法:
你能使用带有string的list作为它的参数去构建一个字符的list(也就是说,每个字符串的长度为一)
thelist = list(thestring)

在python中,字符串是不可变的字符的序列。所以,可以像操作普通的序列一样,按照下标来处理字符。如果要依次处理所有的字符,写一个for循环是效率比较高的方法。
如:
for c in thestring:
do_something_with(c)

更快捷的方法:
results = [do_something_with(c) for c in thestring]


使用build-in的map方法:
results = map(do_something, thestring)

例子:
把一个字符串中的所有字符的ascii码按序列输出.

thestring = 'this is a test'
for c in thestring:
print ord(c),

print [ord(c) for c in thestring]

print map(ord,thestring)

输出的结果如下:

116 104 105 115 32 105 115 32 97 32 116 101 115 116
[116, 104, 105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116]
[116, 104, 105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116]

需要注意的上面的第三种写法,map的第一个参数是一个方法名 ,不带参数,且这个方法必须是callable的.
python中对callable的解释是:

callable(...)
callable(object) -> bool

Return whether the object is callable ( i.e., some kind of function).
Note that classes are callable, as are instances with a __call__() method.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值