python 文本字符串处理

  1. 字符串对齐
  2. 去除字符串首尾字符
  3. 字符串反转

1. 字符串对齐

方法:

  • ljust : 左对齐
  • rjust:右对其
  • center :居中

     

    实例:
    >>> print 'hello'.center(20,'+')
    +++++++hello++++++++
    
    >>> print 'hello'.center(50)   
                          hello
    >>> print 'hello'.rjust(30)
                             hello
    >>> print 'hello'.ljust(30)
    hello
    

2. 去除字符串首尾字符

方法:

  • lstrip : 去除左边字符
  • rstrip : 去除右边字符
  • strip :去除两边字符

     

    实例:
    >>> print '|',x.lstrip( ),'|',x.rstrip( ),'|',x.strip( ),'|'
    | hej      |           hej | hej |
    

3. 字符串反转

方法 :

  • split : 字符串分割
  • join : 连接字符串
  • reversed : 字符串发转

     

    实例 :
    >>> astring = 'a b c d e f g'                              
    >>> revwords1 = ' '.join(astring.split( )[::-1])    实例一
    >>> print revwords1
    g f e d c b a
    >>> revword2 = ' '.join(reversed(astring.split( )))   实例二       
    >>> print revwords1
    g f e d c b a
    

     

last modify 2012-07-10 17:33:34 Tuesday

你可能感兴趣的:(python,字符串处理)