How to handle one character at a time in Python

Source: Internet
Author: User
Tags in python

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/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.