每次处理一个字符
本文地址: http://blog.csdn.net/caroline_wendy/article/details/20359447
用每次处理一个字符的方式处理字符串, 包含四种方法:
1. 使用list, 把字符串转换为字符;
2. for循环, 遍历字符串的每一个字符;
3. 使用集合+for循环的形式, 遍历处理字符串每一个字符;
4. 使用map, 传递函数名, 和字符串, 遍历处理字符串的每一个字符;
获得字符串中所有字符的集合(去重), 使用sets.Set(string)方法.
代码如下:
# -*- coding: utf-8 -*- #==================== #File: PrintExercise.py #Author: Wendy #Date: 2014-03-02 #==================== #eclipse pydev, python2.7 ‘‘‘每次处理一个字符‘‘‘ thestring = "I love you!" #转换为单个字符, 返回集合 thelist = list(thestring) print(thelist) def love(c): u = c.upper() #大写转换 print("{0}".format(u)), #不换行 return u #遍历每个字符进行处理 for c in thestring: love(c) print(‘‘) #返回集合 results = [love(c) for c in thestring] print(results) #返回集合 results_map = map(love, thestring) print(results_map) #去掉重复的字母, 求交集 import sets search = sets.Set("Good Morning!") #去掉重复的字母 object = sets.Set("What are you dong?") print(search) print(object) print(‘‘.join(search&object)) #拼接字符串
输出:
[‘I‘, ‘ ‘, ‘l‘, ‘o‘, ‘v‘, ‘e‘, ‘ ‘, ‘y‘, ‘o‘, ‘u‘, ‘!‘] I L O V E Y O U ! I L O V E Y O U ! [‘I‘, ‘ ‘, ‘L‘, ‘O‘, ‘V‘, ‘E‘, ‘ ‘, ‘Y‘, ‘O‘, ‘U‘, ‘!‘] I L O V E Y O U ! [‘I‘, ‘ ‘, ‘L‘, ‘O‘, ‘V‘, ‘E‘, ‘ ‘, ‘Y‘, ‘O‘, ‘U‘, ‘!‘] Set([‘!‘, ‘ ‘, ‘d‘, ‘G‘, ‘i‘, ‘M‘, ‘o‘, ‘n‘, ‘g‘, ‘r‘]) Set([‘a‘, ‘ ‘, ‘e‘, ‘d‘, ‘g‘, ‘h‘, ‘o‘, ‘n‘, ‘r‘, ‘u‘, ‘t‘, ‘W‘, ‘y‘, ‘?‘]) dgonr