码迷,mamicode.com
首页 > 编程语言 > 详细

Python -- str 类

时间:2016-01-12 15:45:35      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:字符串   python   center   


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‘


本文出自 “纷繁中享受技术的简单喜悦” 博客,请务必保留此出处http://51enjoy.blog.51cto.com/8393791/1734089

Python -- str 类

标签:字符串   python   center   

原文地址:http://51enjoy.blog.51cto.com/8393791/1734089

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!