[Python]Processing a String One Character at a Time

来源:互联网 发布:windows ad域的搭建 编辑:程序博客网 时间:2024/06/06 18:31

Problem
You want to process a string one character at a time.

Solution
You can build a list whose items are the string's characters(meaning that the items are strings, each of length of onePython doesn't have a special type for "characters" as distinct from stirngs). Just call the built-in list, with the string as its argument:

thelist = list(thestring)

You may not even need to build the list, since you can loop directly on the string with a for statement:

for c in thestring:
    do_something_with(c)

or in the for clause of a list comprehension:

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

or, with exactly the same effects as this list comprehension, you can call a function on each character with the map built-in function:

results = map(do_something, thestring)

Discussion
In Python, characters are just strings of length one. You can loop over a string to access each of its characters, one by one. You can use map for much the same purpose, as long as what you need to do with each character is call a function on it. Finally, you can call the built-in type list to obtain a list of the length-one substrings of the string(i.e., the string's characters). If what you want is a set whose elements are the string's characters, you can call sets.set with the string as the argument(in Python 2.4, you can also call the built-in set in just the same way):

import sets
magic_chars 
= set.Set('abracslfjlsjflksdjf')
poppins_chars 
= sets.Set('supercalifragilisticexpialsjlfjslkjflksjfljsdf')
print ''.join(magic_chars & popins_chars)       #set intersection
acrd
原创粉丝点击