[Python]Processing a String One Character at a Time

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值