shanghaipc 发表于 2017-5-5 07:47:28

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

问题:
要一个一个的处理字符串中的字符。
解决方法:
你能使用带有string的list作为它的参数去构建一个字符的list(也就是说,每个字符串的长度为一)
thelist = list(thestring)
在python中,字符串是不可变的字符的序列。所以,可以像操作普通的序列一样,按照下标来处理字符。如果要依次处理所有的字符,写一个for循环是效率比较高的方法。
如:
for c in thestring:
    do_something_with(c)
更快捷的方法:
results =

使用build-in的map方法:
results = map(do_something, thestring)
例子:
把一个字符串中的所有字符的ascii码按序列输出.
thestring = 'this is a test'
for c in thestring:
print ord(c),
print
print map(ord,thestring)
输出的结果如下:
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.
页: [1]
查看完整版本: Python Cookbook 1.1 处理字符串中的字符