Python -- 操作字符串[2/3]

发布时间:2019-09-22 07:54:50编辑:auto阅读(1886)

     

     

    1.split()

     


    1. yuan@ThinkPad-SL510:~$ ipython -nobanner 
    2.  
    3. In [1]: comma_delim_string = "pos1,pos2,pos3" 
    4.  
    5. In [2]: pipe_delim_string = "pipepos1|pipepos2|pipepos3" 
    6.  
    7. In [3]: co 
    8. coerce              compile             continue 
    9. comma_delim_string  complex             copyright 

    按Tab会智能补全的不仅仅是ipython哦,去试试,告诉不了解的童鞋

    1. In [3]: comma_delim_string.split(","
    2. Out[3]: ['pos1''pos2''pos3'
    3.  
    4. In [4]: pipe_delim_string.sp 
    5. pipe_delim_string.split       pipe_delim_string.splitlines 
    6.  
    7. In [4]: pipe_delim_string.split("|"
    8. Out[4]: ['pipepos1''pipepos2''pipepos3'

    split()方法的典型用法即是把希望作为分割符的字符串(注意:是字符串,不一定是一个)传给它。

    补充:split()的第二个参数是分割几次的意思,如下

    1. yuan@ThinkPad-SL510:~$ ipython -nobanner 
    2.  
    3. In [1]: two_field_string ="8675890,This is a freeform, plain text, string" 
    4.  
    5. In [2]: two_field_string.spli 
    6. two_field_string.split       two_field_string.splitlines 
    7.  
    8. In [2]: two_field_string.split(',',1
    9. Out[2]: ['8675890''This is a freeform, plain text, string'
    10.  
    11. In [3]: two_field_string.split(',',2
    12. Out[3]: ['8675890''This is a freeform'' plain text, string'

     

     

    2.upper() and lower()

     


    1. yuan@ThinkPad-SL510:~$ ipython -nobanner 
    2.  
    3. In [1]: mixed_case_string = "VOrpal BUnny" 
    4.  
    5. In [2]: mixed_case_string == "vorpal bunny" 
    6. Out[2]: False 
    7.  
    8. In [3]: mixed_case_string.lower() == "vorpal bunny" 
    9. Out[3]: True 
    10.  
    11. In [4]: mixed_case_string == "VORPAL BUNNY" 
    12. Out[4]: False 
    13.  
    14. In [5]: mixed_case_string.upper() == "VORPAL BUNNY" 
    15. Out[5]: True 

    upper()和lower()并不是简单的返回字符串的大写和小写,它在字符串的比较上有很大作用,想到了吧?呵呵

     

关键字