一个SDET  
每个人都有梦想
  1. 一次处理字符串中一个字符

    你可以建立一个list,其中各项是字符串中字符(在Python中没有字符(characters)和字符串(string)进行区分,字符就是长度为一的字符串)。调用内建的list,字符串为它的参数。
    thelist = list(thestring)

    你甚至可以不需要list,使用for表达式直接在字符串上循环。

    for c in thestring:
        do_something_with(c)

    或者使用list comprehension 中的for子句:

    results = [do_something_with(c) for c in thestring]

    或者,与list comprehension有相同作用的是在内建的map函数中对于每个字符调用一个函数:

    results = map(do_something, thestring)

     

  2. 在字符和数字之间转换,需要将字符转换为它的ASCII码或Unicode码。
    使用内建函数ord和chr:
    >>> print ord('a')
    97
    >>> print chr(97)
    a

    ord也可以接受一个长度为一的Unicode字符串为参数,返回一个Unicode代码值。
    >>> print ord(u'\u2020')
    8224
    使用unichr可以从一个Unicode代码值得到一个长度为一的Unicode字符串。
    >>> print repr(unichr(8224))
    u
    '\u2020'

 


 

 

posted on 2007-01-20 23:07  Ken_Cui  阅读(198)  评论(0)    收藏  举报