问题:
要一个一个的处理字符串中的字符。
解决方法:
你能使用带有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码按序列输出.
输出的结果如下:
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.
要一个一个的处理字符串中的字符。
解决方法:
你能使用带有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.