There are four ways to handle strings with one character at a time:
1. Use list to convert strings to characters;
2. For loop, traversing each character of the string;
3. Use the form of a collection +for loop to iterate through each character of the string;
4. Using map, passing function names, and strings, traversing each character of the processing string;
Gets a collection of all the characters in the string (go Heavy), using sets. Set (String) method.
The code is as follows:
#-*-Coding:utf-8-*-
#====================
#File: printexercise.py
#Author: Wendy
#Date: 2014-03-02
#====================
#eclipse pydev, python2.7 "'
process one character at a time '
thestring =" I Love you! "
#转换为单个字符, returns the collection
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)
#去掉重复的字母, seek intersection
import sets
search = sets. Set ("Good morning!") #去掉重复的字母
object = sets. Set ("What Are you Dong?")
Print (search) print (
object)
print ('. Join (Search&object) #拼接字符串
Output:
[' 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 ', ', ', ', ', ', ', ', ', ', ', W ', ' y ', '? ']
Dgonr
Back to the column page: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/extra/