专栏首页python3Python -- str 类

Python -- str 类

Python str类常用方法:

class str(object):

def capitalize(self):   # 全部字母变小写只有首字母变大写;

                         >>> test = 'PYTHON'

                         >>> test.capitalize()

                         'Python'

def casefold(self): # 全部字母变小写;

                        >>> test = 'PYTHON'

                        >>> test.casefold()

                        'python'

def center(self, width, fillchar=None): # 内容居中,width 总长度,fillchar 空白处

填充内容,默认空;

                        >>> test

                        'PYTHON'

                        >>> test.center(20,'*')

                        '*******PYTHON*******'

def count(self, sub, start=None, end=None):  # 计算字符在字符串中出现的次数,

支持可选长度;

                        >>> test = 'python,python'

                        >>> test.count('py',0,10)

                            2

def  decode(self, encoding='utf-8', errors='strict'):  # 解码

                        >>> test1=test.encode('gbk')

                        >>> test1

                        b'python,python'

                        >>> test1.decode('gbk')

                        'python,python'

def encode(self, encoding='utf-8', errors='strict'):  # 编码

                        >>> test

                        'python,python'

                        >>> test.encode('gbk')

                        b'python,python'

def endswith(self, suffix, start=None, end=None):  # 在字符串中以指定元素结尾则

返回布尔值真,否则返回假;

                        >>> test = 'python,[1,2]'

                        >>> test.endswith('[1]')

                            False

                        >>> test.endswith('[2]')

                            False

                        >>> test.endswith('2]')

                            True

def expandtabs(self, tabsize=8): # 返回字符串的特定格式化,所有的tab被一个或多个

空格代替,默认8个空格;

                        >>> test = '1\t23\t45\t6'

                        >>> test.expandtabs()

                        '1       23      45      6'

                        >>> test.expandtabs(2)

                        '1 23  45  6'

def find(self, sub, start=None, end=None):  # 返回sub在str中所发现的最小索引,

 如果为发现则返回-1;

                        >>> test = 'python,linux,python'

                        >>> test.find('y')

                        1

                        >>> test.find('a')

                        -1

def format(*args, **kwargs):  # 字符串格式化。使用该方法的字符串能够使用括号{}

包含的替换域,每个替换域或者使用位置编号,或者

使用变量名,返回字符串的拷贝,并且所有都被替换

                        >>> test = 'name : {0}, pwd : {1}'

                        >>> test.format('lihongye','pwd1')

                        'name : lihongye, pwd : pwd1'

                        >>> test = 'name : {x}, pwd : {y}'

                        >>> test.format(x='lihongye',y='pwd1')

                        'name : lihongye, pwd : pwd1'

    def format_map(self, mapping):  #

def index(self, sub, start=None, end=None): # 同find,不同是如果没有则返回ValueError;

                        >>> test = 'python,linux,python'

                        >>> test.index('a')

                        Traceback (most recent call last):

                         File "<stdin>", line 1, in <module>

                        ValueError: substring not found

                        >>> test.index('p')

                        0

def isalnum(self):    # 如果是数字、字母则返回True,否则返回False;

                        >>> test = 'x'

                        >>> test.isalnum()

                        True

                        >>> test = 'xy'

                        >>> test.isalnum()

                        True

                        >>> test = '*'

                        >>> test.isalnum()

                        False

def isalpha(self):   # 如果字符串中所有字符都是字母,则返回True,否则返回False;

def isdecimal(self):#如果字符串中所有字符都是十进制数字,则返回True,否则返回False;

def isdigit(self):   # 如果字符串中的所有字符都是数字,则返回True,否则返回False;

def isidentifier(self): #如果字符串中的所有字符都是有效的变量名,则返回True

                              否则返回False;

def islower(self):   # 字符串中的所有字符都是小写,则返回True,否则返回False;

def isnumeric(self):  # 字符串中所有字符都是数字字符,则返回True,否则返回False;

def isprintable(self):  # 字符串为空或者为数字,则返回True,否则返回False;

def isspace(self):  #  如果字符串全为空格,则返回True,否则返回False;

                        >>> test = 'print'

                        >>> test.isspace()

                        False

                        >>> test = ''

                        >>> test.isspace()

                        False

                        >>> test = '    '

                        >>> test.isspace()

                        True

def istitle(self):  # 如果字符串是首字母大写,则返回True,否则返回False;

                        >>> test = 'print'

                        >>> test.istitle()

                        False

                        >>> test = 'Print'

                        >>> test.istitle()

                        True

def isupper(self): # 如果字符串中所有字符全为大写,则返回True,否则返回False;

def join(self, iterable): #  将含有字符串的列表以特定字符串拼接起来形成字符串;

                        >>> test_list = ['1','2','3','4',]

                        >>> '_'.join(test_list)

                        '1_2_3_4'

def ljust(self, width, fillchar=None):  #返回一个适合长度的字符串,使用定义的

                                            字符串向右填充,默认空白;

>>> test

                        'python'

                       >>> test.ljust(10,'*')

                        'python****'

def lower(self):  # 将所有字符串变小写;

def lstrip(self, chars=None):  # 移除字符串左侧空格;

                        >>> test = '  PYTHON  '

                        >>> test.lstrip()

                        'PYTHON  '

def partition(self, sep):  # 从第一个出现的sep开始分离字符串形成三部分:

                                          sep前,sep,sep后

                                如果未找到则返回字符串整体和两个空字符串;

                        >>> test = '1230045600789'

                        >>> test.partition('00')

                        ('123', '00', '45600789')

                        >>> test.partition('a')

                        ('1230045600789', '', '')

def replace(self, old, new, count=None): # 返回一个新的字符串,其中所有的old都被

                                    new代替count用于指定前count个,默认为none全部替换;

                        >>> test

                        '1230045600789'

                        >>> test.replace('0','a',3)

                        '123aa456a0789'

                        >>> test.replace('0','a')

                        '123aa456aa789'

def rfind(self, sub, start=None, end=None): # 返回sub在str中最后出现的索引号,

                                                找不到返回-1;

def rindex(self, sub, start=None, end=None): # 返回sub在str中最后出现的索引号,

                                                找不到返回ValueError;

def rjust(self, width, fillchar=None):  #返回一个适合长度的字符串,使用定义的

                                                字符串向左填充,默认空白;

def rpartition(self, sep):  #从最后一个出现的sep开始分离字符串形成三部分:

                                            sep前,sep,sep后

                                如果未找到则返回字符串两个空字符串和整体;

                        >>> test = '1230045600789'

                        >>> test.rpartition('00')

                        ('12300456', '00', '789')

                        >>> test.rpartition('a')

                        ('', '', '1230045600789')

def rsplit(self, sep=None, maxsplit=-1):  # 使用指定的字符分割字符串形成列表,

                                                从右向左开始分割,指定最大分割个数

                                                未指定分割个数则全部按指定全部分割;

                        >>> test

                        '1230045600789'

                        >>> test.rsplit('0',3)

                        ['1230', '456', '', '789']

def rstrip(self, chars=None): #返回末尾被移除的字符串,默认移除空格,

                                            chars表示移除的字符集;

                        >>> test = '  1230045600789   '

                        >>> test.rstrip()

                        '  1230045600789'

                        >>> test.rstrip('89   ')

                        '  12300456007'

def split(self, sep=None, maxsplit=-1): # 使用指定的字符分割字符串形成列表,

                                                从左向右开始分割,指定最大分割个数

未指定分割个数则全部按指定全部分割;

def splitlines(self, keepends=None):  #按行分割,返回一个包含各行作为元素的列表,

                                            如果num指定则仅切片num个行;

                        >>> test = 'test1\ntest2\ntest3\ntest4\n'

                        >>> print(test)

                        test1

                        test2

                        test3

                        test4

                        >>> print(test.splitlines())

                        ['test1', 'test2', 'test3', 'test4']

                        >>> print(test.splitlines(0))

                        ['test1', 'test2', 'test3', 'test4']

                        >>> print(test.splitlines(1))

                        ['test1\n', 'test2\n', 'test3\n', 'test4\n']

                        >>> print(test.splitlines(2))

                        ['test1\n', 'test2\n', 'test3\n', 'test4\n']

                        >>> print(test.splitlines(3))

                        ['test1\n', 'test2\n', 'test3\n', 'test4\n']

                        >>> print(test.splitlines(4))

                        ['test1\n', 'test2\n', 'test3\n', 'test4\n']

def startswith(self, prefix, start=None, end=None): # 字符串如果以指定字符开头则

                                                        返回True,否则返回False;

def strip(self, chars=None):  #返回字符串并移除首尾字符,默认空白;

def swapcase(self):  # 返回字符串并转换所有字符串的大小写;

def title(self):  # 返回每个单词的首字母大写,其余字母小写;

def translate(self, table):   # (同maketrans一起使用) ;

def maketrans(self, *args, **kwargs): # 用于创建字符映射的转换表,对于接受两个

                                            参数的最简单的调用方式第一个参数是字符集,

                                            表示需要转换的字符,第二个参数也是字符集

表示要转换的目标。两个字符集长度相等一一对应;

            maketrans()方法: transname = str.maketrans(inname,outname)

            translate( )    方法:  str.translate(transname)

                        >>> inname = 'aeiou'

                        >>> outname = '12345'

                        >>> transname = inname.maketrans(outname)

                        >>> test = 'this is a out exam'

                        >>> transname = test.maketrans(inname,outname)

                        >>> transname

                        {97: 49, 111: 52, 117: 53, 101: 50, 105: 51}

                        >>> test.translate(transname)

                        'th3s 3s 1 45t 2x1m'

def upper(self):   # 所有字符都被转换成大写;

def zfill(self, width):   # 返回一个str 的拷贝,长度为width,左边用0填充,

                                    如果字符串以+、-开头则在其后填充0;

                        >>> test = '-53'

                        >>> test.zfill(6)

                        '-00053'

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • python3面向对象注意事项

    2.obj.hello()  #Zzc中执行hello方法 3.Zzc中无hello方法,在父类Yun中寻找hello方法。 4.类Yun中无hello方法,在...

    用户2398817
  • Python 单元测试 & 文档测试

               raise AttributeError(r"'Dict' has no attribute %s." % key)

    用户2398817
  • #5 逆序输出列表内容

    看到逆序输出,想必第一反应就是列表里的第一个元素与最后一个元素交换,接着第二个元素与倒数第二个元素交换......但是有没有更加Pythonic的方法,有,那就...

    用户2398817
  • 十四、social_django 集成第三方登录

    对于template中的用法,向context_processors中加入下面两个

    Freshman
  • Python 单元测试 & 文档测试

               raise AttributeError(r"'Dict' has no attribute %s." % key)

    用户2398817
  • 振幅和成交量的关系

    用广晟有色的历史数据,用sklearn进行回归,数据如下: ? 假设每日振幅和成交量以及价格是有关系的,于是构造: # coding=utf-8 from pa...

    用户1075292
  • 手把手教你从零开始搭建SpringBoot后端项目框架

    打开IDE,点击File -> New Project。在左侧的列表中的选择Maven项目,点击Next。

    SH的全栈笔记
  • Fortran知识 | 代码错误(insufficient virtual memory)

    如图所示,提示为:insufficient virtual memory ? 程序试图访问一个受保护或者不存在的地址。多数为可分配数组、指针等动态内存引发的错误...

    fem178
  • MySQL中使用pt-osc的一些小结

    Percona的pt-osc工具算是DBA的一个福利工具。想想一个数据量有些大的表,在上面做DDL操作真是一种煎熬,我们也基本理解了这是一种空间换时间的...

    jeanron100
  • 第十一节 Go语言数组

    干货来了!!!为了让更多的小伙伴喜欢Golang、加入Golang之中来,Golang语言社区发起人彬哥联合业界大牛共同推出了Go语言基础、进阶、提高课程,目前...

    李海彬

扫码关注云+社区

领取腾讯云代金券