前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 字符串扩展

Python 字符串扩展

作者头像
py3study
发布2020-01-08 17:37:47
1K0
发布2020-01-08 17:37:47
举报
文章被收录于专栏:python3python3

Python 字符串扩展,按照字符串处理效果整理

一、修改字符串字符

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

1)str.capitalize()

    返回字符串的副本,其中第一个字符大写,其余小写。

        >>> 'hello'.capitalize()

        'Hello'

        >>> 'HELLO'.capitalize()

        'Hello'

2)str.lower()

    返回一个字符串的副本,所有包含字符转换为小写。

3)str.islower()

    有且至少有一个小写字符串,返回True,否则False

        >>> 'el lo '.islower()

        True

4)str.strip([chars])

    删除字符串前和后,以 chars 字符串的任意组合,并返回副本,默认删除前后空格。

        >>> 'asdfghjkliuyutre'.strip('srae')

        'dfghjkliuyut'

        >>> '   hello     '.strip()

        'hello'

5)str.lstrip([chars])

    删除左侧字符串,以(chars)任意组合,默认删除空格。

        >>> '   wang   '.lstrip()

        'wang   '

        >>> 'www.baidu.com'.lstrip('comwz')

        '.baidu.com'

6)str.rstrip([chars])

    删除右侧字符串,以(chars)任意组合,默认删除空格。

        >>> '     hello     '.rstrip()

        '     hello'

        >>> 'apple and banana'.rstrip('na')

        'apple and b'

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

    返回一个字符串的副本,所有出现的子字符串old由new替换。 如果给出了可选参数计数,则只替换第一个计数出现次数。

        >>> s.replace('ll','xx')

        'hexxo world'

8)str.swapcase()

    返回大写字符的字符串的副本转换为小写,反之亦然。

        >>> 'Hello'.swapcase()

        'hELLO'

9)str.title()

    返回字符串的拼写版本,其中单词以大写字符开头,其余字符为小写。

        >>> "they're bill's friends from the UK".title()

        "They'Re Bill'S Friends From The Uk"

10)str.istitle()

    每个独立的连续字母段都以大写字母开头,返回True,否则返回False

        >>> 'Hello\tworld'.istitle()

        False

        >>> 'Hello\Tworld'.istitle()

        True

        >>> 'Hello world'.istitle()

        False

11)str.translate(table[, deletechars])

    返回字符串的副本,出现所有字符在可选参数中去除deletechars,并且剩余的字符通过给定映射

    翻译表,它必须是长度为256或无的字符串。如果表参数为None,则不应用和该操作简单地删除deletics中的字符。

        >>> outtab

        '12345'

        >>> trantab=maketrans(intab,outtab)

        >>> str = 'thisssexample...wow!!!!'

        >>> str.translate(trantab,'xm')

        'th3ssse1ple...242!!!!'

        >>> outtab

        '12345'

        >>> trantab=maketrans(intab,outtab)

        >>> str = 'thisssexample...wow!!!!'

        >>> str.translate(trantab,'xm')

        'th3ssse1ple...242!!!!'

12)str.upper()

    字符串转化大写

        >>> 'hello world'.upper()

        'HELLO WORLD'

13)str.isupper()

    字符串都大写,返回True,否则False

二、字符串填充:

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

1)str.center(width)

    返回字符串为中心,两边填充

        >>> ''.center(40,'=')

        '========================================'

2)str.ljust(width[, fillchar])

    返回左对齐字符串,以fillchar填充,默认空格。如width小于或等于len(s),返回原字符串。

        >>> 'wang'.ljust(10)

        'wang      '

3)str.rjust(width[, fillchar])

    字符串右对齐, fillchar填充(默认是一个空格)。 如果width小于或等于len(s),则返回原始字符串。

        >>> s.rjust(40,'+')

        '+++++++++++++++++++++++++++++hello world'

4)str.zfill(width)

    返回长度为width的字符串中以零填充的数字字符串。 正确处理符号前缀。 如果width小于或等于len(s),则返回原始字符串。

        >>> 'wang'.zfill(9)

        '00000wang'

        >>> 'wang'.zfill(3)

        'wang'

三、判定字符串形式,返回True or False

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

1)str.endswith(suffix, start, end)

    如果字符串以指定的后缀结尾,则返回True,否则返回False。 后缀也可以是一个元组的后缀来。 

        'hello world'.endswith('o',0,5)

        True

2)str.startswith(prefix[, start[, end]])

    如果字符串以前缀开头,则返回True,否则返回False。 前缀也可以是要查找的前缀的元组。可定义范围。

        >>> 'helloworld'.startswith('l')

        False

        >>> 'helloworld'.startswith('h')

        True

3)str.isalnum()

    如果字符串中的所有字符都是字母数字且至少有一个字符,则返回true,否则返回false。

        >>> 'hello world1'.isalnum()

        False

        >>> 'helloworld1'.isalnum()

        True

4)str.isalpha()

    如果字符串中的所有字符都是字母并且至少有一个字符,则返回true,否则返回false。

        >>> 'hello'.isalpha()

        True

        >>> 'hello1'.isalpha()

        False

5)str.isdigit()

    如果字符串中的所有字符都是数字,并且至少有一个字符,则返回true,否则返回false。

6)str.isspace()

    如果字符串中只有空格字符并且至少有一个字符,则返回true,否则返回false。

四、字符串统计查找:

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

1)str.count(sub, start, end)

    统计字符个数,可切片定义范围

        >>> 'hello world'.count('l')

        3

2)str.find(sub,start,end)

    返回字符串最小索引,找不到返回-1,当你知道sub位置,可用find,检查是否是子字符串,用 in 

        >>> 'helloworld'.find('l',0,3)

        2

3)str.rfind(sub[, start[, end]])

    返回找到的最高索引,找不到 返回 -1

        >>> 'hello world'.rfind('l')

        9

4)str.index(sub, start, end)

    找不到返回ValueError

5)str.rindex(sub[, start[, end]])

    类似于s.rfdind(),找不到跑出 ValueErro

五、字符串添加分隔符:

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

1)str.join(iterable)

    返回以interable为分隔符的字符串

        >>> 'wang'.join('HHH')

        'HwangHwangH'

2)str.partition(sep)

    字符串查找sep,返回它之前部分,本身,其后部分,若未发现字符串,返回字符串本身和两个空字符串。

        >>> 'helloworld'.partition('w')

        ('hello', 'w', 'orld')

        >>> 'helloworld'.partition('x')

        ('helloworld', '', '')

3)str.rpartition(sep)

    在S中搜索分隔符sep,从S结尾开始,然后返回其前面的部分,分隔符本身和其后的部分。 如果

    分隔符没有找到,返回两个空字符串和S.

        >>> 'helloworld'.rpartition('r')

        ('hellowo', 'r', 'ld')

        >>> 'helloworld'.rpartition('z')

        ('', '', 'helloworld')

4)str.split([sep[, maxsplit]])

    返回字符串中的单词的列表,使用sep作为分隔符字符串。 如果给定maxsplit,最多拆分maxsplit次。 

    如果sep未指定或为无,任何whitespace string是一个分隔符,空字符串被删除从结果。

        >>> 'helloworld'.split('o',)

        ['hell', 'w', 'rld']

        >>> 'helloworld'.split('o',1)

        ['hell', 'world']

5)str.rsplit([sep[, maxsplit]])

    返回字符串中的单词的列表,使用sep作为分隔符字符串,从字符串结尾处开始工作

    到前面。 如果给出了maxsplit,则最多maxsplit分裂为完成。 如果sep未指定或为无,

        则为任何空格字符串是一个分隔符。

        >>> 'hello world'.rsplit()

        ['hello', 'world']

        >>> 'hello world'.rsplit('l')

        ['he', '', 'o wor', 'd']

6)str.splitlines([keepends])

    返回S中的行的列表,在行边界处折行。除非保留,换行符不包括在结果列表中是真实的。

    Python将“\ r”,“\ n”和“\ r \ n”识别为8位字符串的行边界。

        >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()

        ['ab c', '', 'de fg', 'kl']

        >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(True)

        ['ab c\n', '\n', 'de fg\r', 'kl\r\n']

        >>> "".splitlines()

        []

        >>> "one lines\n".splitlines()

        ['one lines']

        >>> ''.splitlines()

        []

        >>> ''.split('\n')

        ['']

        >>> 'two lines\n'.split('\n')

        ['two lines', '']

7)S.expandtabs([tabsize])-> string

    把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是8,tabsize -- 指定转换字符串中的 tab 符号('\t')转为空格的字符数。

        S.expandtabs([tabsize])-> string

        >>> '01\t012\t0123\t01234'.expandtabs()

        '01      012     0123    01234'

        >>> '01\t012\t0123\t01234'.expandtabs(4)

        '01  012 0123    01234'

六、字符串转码:

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

1)str.encode()

    使用encode()则可以将 unicode 字符串 转换成 str 类型的 plain string

        >>> u = u'你好'

        >>> s = u.encode('gbk')

        >>> type(u)

        <type 'unicode'>

        >>> type(s)

        <type 'str'>

        >>> u

        u'\u4f60\u597d'

        >>> s

        '\xc4\xe3\xba\xc3'

        >>> print u

        你好

        >>> print s

        你好

         >>> len(u)

        2

        >>> len(s)

        4

2)str.decode(encoding,error)

    以指定的编码格式解码字符串。默认编码为字符串编码(适合python2中处理中文)

        >>> s = '你好'

        >>> u = s.decode('gbk')

        >>> type(s)

        <type 'str'>

        >>> type(u)

        <type 'unicode'>

        >>> print s

        你好

        >>> print u

        你好

        >>> s

        '\xe4\xbd\xa0\xe5\xa5\xbd'

        >>> u

        u'\u6d63\u72b2\u30bd'

        >>> len(s)

        6

        >>> len(u)

        3

七、字符串格式化

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

1)str.format(*args, **kwargs)

    大括号为分隔符,并且对应相应索引

        >>> name = 'StivenWang'

        >>> fruit = 'apple'

        >>> print 'my name is {},I like {}'.format(name,fruit)

        my name is StivenWang,I like apple

        >>> print 'my name is {1},I like {0}'.format(fruit,name)

        my name is StivenWang,I like apple

        >>> print 'my name is {mingzi},I like{shuiguo}'.format(shuiguo=fruit,mingzi=name)

        my name is StivenWang,I like apple   

2)unicode.splitlines([keepends])

    返回字符串中的行的列表,如str.splitlines()。 但是,Unicode方法分割在以下行边界上,它们是为8位字符串识别的通用换行符的超集。

        Representation Description

        \n Line Feed

        \r Carriage Return

        \r\n Carriage Return + Line Feed

        \v or \x0b Line Tabulation

        \f or \x0c Form Feed

        \x1c File Separator

        \x1d Group Separator

        \x1e Record Separator

        \x85 Next Line (C1 Control Code)

        \u2028 Line Separator

        \u2029 Paragraph Separator    

****以下方法仅存在于unicode对象上:

1)unicode.isnumeric()

    如果S中只有数字字符,则返回True,否则返回False。 数字字符包括数字字符,以及具有Unicode数字值属性的所有字符。 U + 2155,VULGAR FRACTION ONE FIFTH。

        >>> u'123'.isnumeric()

        True

        >>> u'wang'.isnumeric()

        False

2)unicode.isdecimal()

    如果S中只有十进制字符,返回True,否则返回False。 小数字符包括数字字符,以及可用于形成十进制数字的所有字符。 U + 0660,ARABIC-INDIC DIGIT ZERO。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档