• Python的字符串


    Python有内置的字符串类型, 内置的字符串是序列(Sequence), 是不可变的序列,  所以不可变序列通用的方法对其都适用.

    对Python2, 内置的字符串类型有strunicode

    Python2

    'abc' 是str, u'中国123'  是unicode

    # Python2.7
    >>> type('abc')
    <type 'str'>
    >>> type(u'中国123')
    <type 'unicode'>

    如果我们使用Python2, 应该都尽量使用unicode,就算是纯英文的. 

     

    Python3

    但在Python3中, 没有预定义unicode类型了,内置字符串就是str, 但是str中的字符都是unicode编码的 

    #Python3.3
    >>> type(u'中国')
    <class 'str'>
    >>> type('abc')
    <class 'str'>
    >>> type(str)
    <class 'type'>
    >>> type(unicode)
    NameError: name 'unicode' is not defined

    下面讨论一些Python内置字符串常用的方法, Python2中这些方法对str和unicode基本都是一样的, 没有讨论到的去文档查阅就行,基本上需要的功能都有方法实现.

    字符串分隔, split

    str.split()接受分隔字符串, 返回分隔后的一个list

    >>> s = 'wangyu@lvye.cn'
    >>> s.split('@')
    ['wangyu', 'lvye.cn']

    如果同一个分隔符连续多个存在,则在返回结果中会有空字符串

    >>> s = 'wangyu@@@@lvye.cn'
    >>> s.split('@')
    ['wangyu', '', '', '', 'lvye.cn']

    4个连续的@产生了3个空串

    当分隔字符串是多字符的,必须是全匹配

    >>> s = 'abc<>cba'
    >>> s.split('<>')
    ['abc', 'cba']

     一个反面例子

    >>> s = 'abc<>cba%$acb'
    >>> s.split('<>$')
    ['abc<>cba%$acb']

    str.split()也可以不接受参数,这时候是使用空格做分隔,且不产生空串,如果开头和结尾有空格,也会被忽略掉

    >>> s = ' we are the   champion'
    >>> s.split()
    ['we', 'are', 'the', 'champion']

    子串替换

      str.replace(old, new [, count])

    replace把old替换成new,并且可以指定替换个数, 而且函数返回一个copy,不会影响原来的str对象.

    >>> s = 'he is nate, nate is his name'
    >>> s.replace('nate', 'sky')
    'he is sky, sky is his name'
    >>> s
    'he is nate, nate is his name'

    子串查找

    字串查找用find()或index(),  其中index()是序列通用的方法

    不同的是若没找到find()返回-1, index()抛出异常ValueError, 找到返回字串索引.

    find()和index()的语法相同

    str.find(substr [, start [, end]])

    普通使用

    >>> s='we are are the champion'
    >>> s.find('ar')
    3

    加上范围

    >>> s='we are are the champion'
    >>> s.find('ar', 4)
    7

    注意,如果只是想知道一个字符串是否包含一个子串,使用 in 

    >>> s = 'we are the champion'
    >>> 'are' in s
    True

    字符串的strip

    同样的strip会copy一份原来的字串进行处理.

    不加任何参数,去除左右的空格

    >>> s = '    www.lvye.cn  '
    >>> s.strip()
    'www.lvye.cn'

    带上参数

    >>> s.strip('wcn. ')
    'lvye'

    注意带上参数时,空格要显示指定.

    strip还可以去除两端的换行符

    字符串其它的方法

    •  isalpha()  是否都是字母
    •  isdigit()    是否都是数字
    •  upper()    都转化为大写

    Python str的方法,Python文档中很全.

    ------------------------- 

     参考:

    http://docs.python.org/3/library/stdtypes.html#str   Python文档

  • 相关阅读:
    _STORAGE_WRITE_ERROR_:./Application/Runtime/Cache/Home/f8995a0e1afcdadc637612fae5a3b585.php
    git 报错:没有权限 remote: error: unable to unlink old 'README.md' (Permission denied)
    深度学习入门实战(二)-用TensorFlow训练线性回归
    一条SQL搞定信息增益的计算
    Vue.js动画在项目使用的两个示例
    腾讯云安全:开发者必看|Android 8.0 新特性及开发指南
    腾讯云上Selenium用法示例
    一个只有99行代码的JS流程框架
    腾讯云上PhantomJS用法示例
    前端开发框架简介:angular和react
  • 原文地址:https://www.cnblogs.com/livingintruth/p/3282981.html
Copyright © 2020-2023  润新知