zoukankan      html  css  js  c++  java
  • Python String Methods

    1. str.capitalize()

      # 将字符串的第一个字母变成大写,其他字母变小写。对于 8 位字节编码需要根据本地环境
    >>> 'hello'.capitalize()
    'Hello'
    >>> 'hEllo'.capitalize()
    'Hello
    View Code

    2. center(width[, fillchar])

    # 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格
    >>> 'hello'.center(10,'0')
    '00hello000'
    >>> 'hello'.center(10)
    '  hello   '
    View Code

    3. count(sub, start= 0,end=len(string)

    #方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置
    >>> 'hello world'.count('o')
    2
    >>> 'hello world'.count('o',4,8)
    2
    >>> 'hello world'.count('o',4,7)
    1
    View Code

    4. decode(encoding='UTF-8',errors='strict')  encode(encoding='base64',errors='strict')

    #以 encoding 指定的编码格式解码字符串。默认编码为字符串编码    
    encoding -- 要使用的编码,如"UTF-8"。
    errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。
    >>> 'hello'.encode('base64','strict')
    'aGVsbG8=
    '
    >>> 'hello'.decode('UTF-8','strict')
    u'hello'
    View Code

    5. endswith(suffix[, start[, end]])

     # 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置
    # 自Python2.5版本起,还支持接收一个 tuple 为参数
     1 >>> 'hello'.endswith('lo')
     2 True
     3 >>> 'hello'.endswith('ll')
     4 False
     5 >>> 'hello world'.endswith('or',2,8)
     6 False
     7 >>> 'hello world'.endswith('or',2,9)
     8 True
     9 >>> a=('or','ox','oy','ld')
    10 >>> 'hello world'.endswith(a)
    11 True
    View Code

    6. expandtabs(tabsize=8)

    # 方法把字符串中的 tab 符号('	')转为空格,默认的空格数 tabsize 是 8
     >>> 'hello	world'.expandtabs(8)
    'hello   world'
     >>> 'hello	world'.expandtabs(16)
     'hello           world'
    View Code

     7. find(str, beg=0 end=len(string))

    #方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1
    
    >>> 'hello world'.find('llo')
    2
    >>> 'hello world'.find('lloo')
    -1
    >>> 'hello world'.find('llo',2,4)
    -1
    >>> 'hello world'.find('llo',2)
    2
    View Code

     8. index(sub[, start[, end]])

    #Like find(), but raise ValueError when the substring is not found.
    # 查找字符串中是否有子字符串sub,如果有返回sub的索引位置,如果没找到则返回具体错误
    >>> 'hello world'.index('wo')
    6
    >>> 'hello world'.index('wx')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: substring not found
    View Code
  • 相关阅读:
    静态与动态数据分析的测试方法
    网址无法访问,显示服务器拒绝了请求
    stf浏览器端删除离线设备
    STF日志提示 Not found ; no service started
    通过adb命令获取apk的安装路径
    js页面打开方式
    windows和mac回退及撤销快捷键
    单元测试规范
    Git :fatal: refusing to merge unrelated histories解决
    mysql详解4:分组
  • 原文地址:https://www.cnblogs.com/njuptlwh/p/7802621.html
Copyright © 2011-2022 走看看