python基础篇之字符串

 |   

个人感觉 Python 对字符串的处理是非常强的,所以掌握一些 Python 对字符串的基本操作是非常有必要的.

字符串表示

  • 赋值

    1str = 'hello'
    
  • 填字符串

    1str = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')
    
  • 转换

    1pi = 3.14
    2print 'pi = ' + str(pi)
    

常用方法

  • 大小写转换

    1str.lower()
    2str.upper()
    
  • 去除首尾空格

    1str.strip()
    
  • 判断字符里所有的字符是不是字母/数字/空格

    1str.isalpha()
    2str.isdigit()
    3str.isspace()
    
  • 判断字符串是不是以某个子串开头/结尾

    1str.startswith(' ')
    2str.endswith()
    
  • 查找子串在字符串中的位置,没找到返回-1

    1str.find('th')
    
  • 字符串的替换

    1str.replace('old','new')
    
  • 字符串的分割,返回 list

    1str.split('delim')
    2'delim'.join(list)
    3
    

编码问题

在 Python2 里面默认都是用 unicode 编码的,而 windows 里面的文件默认是 gbk 编码,而 linux 里面的文件默认的是 utf8 编码,所以编码之间的转换是必不可少的.

  • 定义unicode字符串

    1ustr = u'A unicode \u018e string \xf1'
    
  • 转换utf-8编码

    1utfstr = ustr.encode('utf-8')
    
  • 转换会unicode编码

    1unistr = unicode(utfstr, 'utf-8')
    

课后练习

技术茶话会
< 前一篇 后一篇 >