zoukankan      html  css  js  c++  java
  • day1 str字符串常用方法

        字符串是编程中常用的类型,字符型在内存中是以单个形式存储的,比如name = "alex",在内存中存储的形式为["a","l","e","x"],因此我们可以使用列表的很多功能来操作字符串,因为我开始的时候一直在想为什么字符串可以使用切片,可以有索引,开始的时候一直不明白,后来知道了Python字符串的存储形式之后才明白为什么存在这些方法。下面我们来看看字符串类型中包含那些方法:

        在Python中有些方法下面有注释,这是因为这些方法使用Python自己编写的,我们知道Python中很多是直接调用C语言中的方法,看不到的那些是C语言中的方法。

        1.capitalize(self)

        def capitalize(self): # real signature unknown; restored from __doc__
        """
        S.capitalize() -> str
            首字母大写,只是第一个居首第一个首字母大写
        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.
        """
        return ""

        capitalize(self)是居首首字母大写,我们知道还有一个方法title(),下面来比较这两个方法的不同点:

        >>> name = "alex is sb"
      >>> name.capitalize()
      'Alex is sb'
      >>> name.title()
      'Alex Is Sb'

        从上面可以看出,capitalize(self)是居首首字母大写,其他字母不大写;而title(self)方法是所有单词的首字母都大写,这个在用的时候要知道是要求那么字母大写。

        2.casefold(self)

        def casefold(self): # real signature unknown; restored from __doc__
        """
        S.casefold() -> str
            所有首字母小写,等价于lower()
        Return a version of S suitable for caseless comparisons.
        """
        return ""

        casefold(self)是将大写字母转化为小写,等价于lower(self),实例如下:

        >>> name = "ALEX Is SB"
      >>> name.casefold()
      'alex is sb'
      >>> name
      'ALEX Is SB'
      >>> name.lower()
      'alex is sb'

      3.center(self,width,fillchar=None)

        def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.center(width[, fillchar]) -> str
            """center(self,width,fillchar=None)是将字符串放到中间,两边加上任意符号,默认空格"""
        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""

        center(self,width,fillchar=None),美化格式,把self放到中间,指定任意长度的字符,空白处用字符填充,默认时空字符。示例如下:

        >>> name = "您好"
      >>> name.center(12)
      '     您好     '
      >>> name.center(12,"-")
      '-----您好-----'

        4.__format__(self,format_spec)

        def __format__(self, format_spec): # real signature unknown; restored from __doc__
        """
        S.__format__(format_spec) -> str
            字符串的格式化
        Return a formatted version of S as described by format_spec.
        """
        return ""

        __format__(self,format_spec)字符串进行格式化,按照我们要求的格式进行字符串格式化操作。详细可参考(http://www.cnblogs.com/nulige/p/6115793.html)

        >>> tp1 = "My name is {0},and I am {1} years old,I am {2}"
      >>> tp1.format("Alex","18","sb")

        'My name is Alex,and I am 18 years old,I am sb'

        >>> tp2 = "I am {1} years old,my name is {2},and I am {0}."
      >>> tp2.format("sb","18","Alex")
      'I am 18 years old,my name is Alex,and I am sb.'
        这种方法也可以用在字符串的拼接上面,使用字符串的format()方法,在{}大括号中定义索引,告诉Python把哪个值传给索引位置。

        5.__getattribute__(self,*args,**kwargs)

        def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """

            """反射的时候用的"""
        pass

        6.__getitem__(self,*args,**kwargs)

        def __getitem__(self, *args, **kwargs): # real signature unknown
        """ Return self[key]. """

        """得到字符串低级个元素,等价于self[key]"""
        pass
     

        就是获取字符串中第几个位置的字符,我们知道字符串在内存中是以列表形式存储的,因此可以使用索引来获取单个字符,实例如下:

        >>> name = "Alexissb"
      >>> name.__getitem__(2)
      'e'
      >>> name[2]
      'e'
        字符串中索引是从0开始的,获取字符串中第几个位置的字符。

        7.__getnewargs__(self,*args,**kwargs)

        def __getnewargs__(self, *args, **kwargs): # real signature unknown

        """__getnewargs__是跟参数有关的"""
        pass

        8.__hash__(self,*args,**kwargs)

        def __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self). """
        pass
       

        9.__iter__(self,*args,**kwargs)

        def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

        10.__len__(self,*args,**kwargs)

        def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """

            """返回字符串的长度,等价与len(self)"""
        pass

        实例如下:

        >>> name = "Alexissb"
      >>> name.__len__()
      8
      >>> len(name)
      8
        11.count(self,sub,start=None,end=None)
        def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.count(sub[, start[, end]]) -> int

            返回在字符串中出现指定字符的个数,返回一个整数

        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end]. Optional arguments start and end are
        interpreted as in slice notation.
        """
        return 0

        count(self,sub,start=None,end=None)是用来统计字符串中出现特定字符的个数,返回一个整数,实例如下:

        >>> name = "Alexssbbafadgcxlsdgpssl"
        >>> name.count("a")
      2
        >>> name.count("D")
      0
        统计字符串中出现指定字符的个数,当不存在的时候返回0。

        12.encode(self,encoding='utf-8',errors='strict')

        def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
        """
        S.encode(encoding='utf-8', errors='strict') -> bytes
            编码
        Encode S using the codec registered for encoding. Default encoding
        is 'utf-8'. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
        """
        return b""

        实例如下:

        >>> name = "李杰"
      >>> name.encode("gbk")
      b'xc0xeexbdxdc'
        将字符串转化为"gbk"格式,机器识别的格式。

        13.endswith(self,suffix,start=None,end=None)

        def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.endswith(suffix[, start[, end]]) -> bool
            字符串是否以指定的字符结束,endswith(self,suffix,start=None,end=None)
        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False

        endswith(self,suffix,start=None,end=None)判断字符串以某个指定的字符结束,如果是,则返回布尔值True;否则返回False。

        >>> name = "Alexsssbdfgedlmnopqqsstabsc"
      >>> name.endswith("c")
      True
      >>> name.endswith("s",0,5)
      True
        14.expandtabs(self,tabsize=8)

        def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
        """
        S.expandtabs(tabsize=8) -> str
            将字符串中的tab键转化为空格,默认时8个位置的空格,可以自己设置参数
        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""

        expandtabs(self,tabsize=8)将字符串中的tab( )将转化为空格,默认是转化为8个空格,可以自己设置转化为几个空格。示例如下:

        >>> user = "    Alex"
      >>> user.expandtabs()
      '        Alex'
      >>> user.expandtabs(2)
      '  Alex'
      >>> user.expandtabs(0)
      'Alex'
      >>> user.expandtabs(tabsize=3)
      '   Alex'
        15.find(self,sub,start=None,end=None)

        def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.find(sub[, start[, end]]) -> int
            查找指定字符在字符串中的位置,返回位置索引,如果查找不到,则返回-1(return -1 on failure)
        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end]. Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0

        find(self,sub,start=None,end=None)查找指定字符在字符串中的位置,如果查找不到,则返回-1(即查找字符不存在指定字符串中),示例如下:

        >>> name
      'Alexsssbdfgedlmnopqqsstabsc'
      >>> name.find("s")
      4
      >>> name.find("s",8,len(name)-1)
      20
      >>> name.find("S")
      -1
        find(self,sub,start=None,end=None)查找这个字符第一次出现的位置索引。只查找第一个位置索引,查找失败返回-1.
        16.index(self,sub,start=None,end=None)

        def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.index(sub[, start[, end]]) -> int
           
        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0

          index(self,sub,start=None,end=None)跟find()一样是查找指定字符在字符串中的位置索引,不同的是,如果index()查找失败,则报错。查找不到报错。  示例如下:

         >>> name
      'Alexsssbdfgedlmnopqqsstabsc'
      >>> name.index("s")
      4
      >>> name.index("s",8,len(name)-1)
      20
      >>> name.index("S")
      Traceback (most recent call last):
         File "<stdin>", line 1, in <module>
      ValueError: substring not found
        上面可以看出,index()和find()是一样的,都是返回查找字符的位置索引,但是当index()查找不到的时候会报错。

        17.format_map(self,mapping)

        def format_map(self, mapping): # real signature unknown; restored from __doc__
        """
        S.format_map(mapping) -> str

        Return a formatted version of S, using substitutions from mapping.
        The substitutions are identified by braces ('{' and '}').
        """
        return ""

        18.isalnum(self)

        def isalnum(self): # real signature unknown; restored from __doc__
        """
        S.isalnum() -> bool
           判断字符串中所有的字符是否都是字符数字组成
        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False

        示例如下:判断字符串中是否所有元素只有数字和字母组成,alnum是单词alphanumeric的缩写,字母数字
        >>> name.isalnum()
      True
      >>> nums = "2233"
      >>> nums.isalnum()
      True

        19.isalpha()

        def isalpha(self): # real signature unknown; restored from __doc__
        """
        S.isalpha() -> bool
            判断字符串中所有的元素是否都是字母组成
        
    Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
     
       return False

        判断字符串所有字符是否都是字母alpha是单词alphabetic(字母)的缩写:  

    >>> nums = "2233"
      >>> name.isalpha()
      True
      >>> nums.isalpha()
      False
        20.isdecimal(self)

        def isdecimal(self): # real signature unknown; restored from __doc__
        """
        S.isdecimal() -> bool
            如果字符串中值包含十进制的数字,则返回True;否则返回布尔值False.
        Return True if there are only decimal characters in S,
        False otherwise.
        """
        return False

        isdecimal(self)判断字符串中是否只包含十进制的数字,如果是,则返回True;否则返回False。示例如下:

        >>> s1 = "a122"
      >>> s2 = "222"
      >>> s3 = "&b#s"
      >>> s1.isdecimal()
      False
      >>> s2.isdecimal()
      True
      >>> s3.isdecimal()
      False
        21.isdigit(self)
        def isdigit(self): # real signature unknown; restored from __doc__
        """
        S.isdigit() -> bool
            判断字符串是否仅仅由数字组成
        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False

        isdigit(self)判断字符串中是否仅仅包含数字,即由数字组成的字符串。实例如下:

        >>> s1 = "a122"
      >>> s2 = "222"
      >>> s3 = "&b#s"

        >>> s1.isdigit()
      False
      >>> s2.isdigit()
      True
      >>> s3.isdigit()
      False
        22.isidentifier(self)

        def isidentifier(self): # real signature unknown; restored from __doc__
        """
        S.isidentifier() -> bool

        Return True if S is a valid identifier according
        to the language definition.


        Use keyword.iskeyword() to test for reserved identifiers
        such as "def" and "class".
        """
        return False

        isidentifier(self),实例如下:

        >>> s2 = "Alex"
      >>> s3 = "list"
      >>> s2.isidentifier()
      True
      >>> s3.isidentifier()
      True
      >>> s4 = "55"
      >>> s4.isidentifier()
      False
      >>> s5 = "gengcx"
      >>> s5.isidentifier()
      True

        23.islower(self)

        def islower(self): # real signature unknown; restored from __doc__
        """
        S.islower() -> bool
            判断是否都是小写
        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

        islower(self)判断字符串是否都是小写,

        >>> s1 = "Alex"
      >>> s2 = "23abc"
      >>> s3 = "alex"
      >>> s4 = "AlexSb&&"
      >>> s5 = "a%@"
      >>> s1.islower()
      False
      >>> s2.islower()
      True
      >>> s3.islower()
      True
      >>> s4.islower()
      False
      >>> s5.islower()
      True
        24.isnumeric(self)

        def isnumeric(self): # real signature unknown; restored from __doc__
        """
        S.isnumeric() -> bool

        Return True if there are only numeric characters in S,
        False otherwise.
        """
        return False

        isnumeric(self)判断字符串S中是否值包含数字在里面,如果是,返回True;否则返回False.

        >>> name = "Alex222"
      >>> nums = "234239"
      >>> num = "23se"
      >>> l1 = "2.35"
      >>> name.isnumeric()
      False
      >>> nums.isnumeric()
      True
      >>> num.isnumeric()
      False
      >>> l1.isnumeric()
      False
        25.isprintable(self)

        def isprintable(self): # real signature unknown; restored from __doc__
        """
        S.isprintable() -> bool
           判断一个字符串是否里面的字符都是可以打印出来的或者字符串是空的,如果是返回True;否则返回False
        Return True if all characters in S are considered
        printable in repr() or S is empty, False otherwise.
        """
        return False

        isprintable(self) 

        >>> name = "    Alex"
      >>> name.isprintable()
      False
      >>> user = "Alex"
      >>> user.isprintable()
      True

        >>> s1 = ""
        >>> s1.isprintable()
      True
        isprintable(s1)中s1是空的字符串,但是也返回True.
        26.isspace(self)

        def isspace(self): # real signature unknown; restored from __doc__
        """
        S.isspace() -> bool
            判断字符串中是否都是空白
        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False

        isspace(self)判断字符串中是否都是空白,如果是返回True;否则返回False。示例如下:

        >>> s1 = "    "
      >>> s2 = "       "
      >>> s3 = "cs   "
      >>> s1.isspace()
      True
      >>> s2.isspace()
      True
      >>> s3.isspace()
      False
        27.istitle(self)

        def istitle(self): # real signature unknown; restored from __doc__
        """
        S.istitle() -> bool
            判断字符串中所有字符是否是首字母大写形式,如果是返回True
        Return True if S is a titlecased string and there is at least one
        character in S, i.e. upper- and titlecase characters may only
        follow uncased characters and lowercase characters only cased ones.
        Return False otherwise.
        """
        return False

        istitle(self)判断是否首字母大写,如果是返回True;否则返回False。实例如下:

        >>> s1 = "Alex is sb"
      >>> s2 = "Alex Is Sb"
      >>> s3 = "alex is sb"
      >>> s1.istitle()
      False
      >>> s2.istitle()
      True
      >>> s3.istitle()
      False
        28.isupper(self)

        def isupper(self): # real signature unknown; restored from __doc__
        """
        S.isupper() -> bool
            判断所有字母是否都是大写
        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

          isupper(self)判断字符串中所有字符是否都是大写形式:实例如下:

        >>> s1 = "Alex is sb"
      >>> s2 = "Alex Is Sb"
        >>> s3 = "alex is sb"

        >>> s4 = "ALEX IS SB"
        >>> s1.isupper()
      False
      >>> s2.isupper()
      False
      >>> s3.isupper()
      False

        >>> s4.isupper()
      True

        29.join(self,iterable)

        def join(self, iterable): # real signature unknown; restored from __doc__
        """
        S.join(iterable) -> str
            字符串的拼接,把字符串拼接到一起
        Return a string which is the concatenation of the strings in the
        iterable. The separator between elements is S.
        """
        return ""

        join(self,iterable)拼接,字符串和列表直接的拼接,有不同方式的拼接,下面来研究一下:

        >>> sign = "-"
      >>> name = "alex"
      >>> li = ["a","l","e","x","s","b"]
      >>> l1 = ""
        1.字符串和字符串进行拼接,将拼接中的字符串的每一个元素与字符串中的元素进行拼接,即iterable+self+iterable+self... 

      >>sign.join(name)
      'a-l-e-x'
      >>> name.join("sb")
      'salexb'
      >>> name.join("issb")
      'ialexsalexsalexb'
      2.字符串和列表进行拼接,列表中的每一个元素都与字符串的元素进行拼接:

      >>> sign.join(li)
      'a-l-e-x-s-b'
      >>> l1.join(li)
      'alexsb'

        其实在Python中,字符串存储的格式就是列表存储的,比如"alexsb"存储就是["a","l","e","x","s","b"],因而字符串与列表拼接与字符串与字符串拼接是一样的。

        30.ljust(self,width,fillchar=None)

        def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.ljust(width[, fillchar]) -> str
           固定长度,字符串左边拼接指定的字符
        Return S left-justified in a Unicode string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""
        ljust(self,width,fillchar=None),固定长度,self+fillchar,实例如下:

        >>> name = "alexsb"
        >>> name.ljust(12,"-")
      'alexsb------'

        31.rjust(self,width,fillchar=None)

        def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.rjust(width[, fillchar]) -> str

        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

        固定字符串长度,在字符串左侧链接指定字符,实例如下:

        >>> name = "alexsb"   

      >>> name.rjust(12,"-")
      '------alexsb'

        32.lower(self)

        def lower(self): # real signature unknown; restored from __doc__
        """
        S.lower() -> str
            将字符串全部转化为小写形式
        Return a copy of the string S converted to lowercase.
        """
        return ""

        33.lstrip(self,chars=None)

        def lstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.lstrip([chars]) -> str

        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

        lstrip(self,chars=None)是删除字符串左侧的空格,默认是删除空格,其实可以指定删除任何字符,实例如下:

        >>> name = "   AlexAesbb   "
      >>> name.lstrip()
      'AlexAesbb   '

        34.rstrip(self,chars=None)

        def rstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.rstrip([chars]) -> str
            删除字符串右侧的空格
        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

        rstrip(self,chars=None)删除字符串右侧的空格,实例如下:

        >>> name = "   AlexAesbb   "   

        >>> name.rstrip()
    '   AlexAesbb'

        35.strip(self,chars=None)

        def strip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.strip([chars]) -> str

        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

         strip(self,chars=None)删除字符串两侧的空格,示例如下:

        >>> name = "   AlexAesbb   "   

        >>> name.strip()
      'AlexAesbb'

        36.maketrans(self,*args,**kwargs)

        def maketrans(self, *args, **kwargs): # real signature unknown
        """
        Return a translation table usable for str.translate().

        If there is only one argument, it must be a dictionary mapping Unicode
        ordinals (integers) or characters to Unicode ordinals, strings or None.
        Character keys will be then converted to ordinals.
        If there are two arguments, they must be strings of equal length, and
        in the resulting dictionary, each character in x will be mapped to the
        character at the same position in y. If there is a third argument, it
        must be a string, whose characters will be mapped to None in the result.
        """
        pass

        37.translate(self,table)

        def translate(self, table): # real signature unknown; restored from __doc__
        ""
        S.translate(table) -> str

        Return a copy of the string S in which each character has been mapped
        through the given translation table. The table must implement
        lookup/indexing via __getitem__, for instance a dictionary or list,
        mapping Unicode ordinals to Unicode ordinals, strings, or None. If
        this operation raises LookupError, the character is left untouched.
        Characters mapped to None are deleted.
        """
        return ""

        示例如下:

        >>> intab = "aeiou"
      >>> outtab = "12345"

        >>> trantab = intab.maketrans(intab,outtab)
      >>> trantab
      {97: 49, 111: 52, 117: 53, 101: 50, 105: 51}

        >>> str = "This is string example .... wow!!!"
        >>> str.translate(trantab)
      'Th3s 3s str3ng 2x1mpl2 .... w4w!!!'

        上面代码含义是,把intab中每个元素与outtab中每个元素一一对应,然后translate()替换其中对应的元素。

        38.partition(self,sep)

        def partition(self, sep): # real signature unknown; restored from __doc__
        """
        S.partition(sep) -> (head, sep, tail)
            字符串分隔,以sep分隔为前中后三部分
        Search for the separator sep in S, and return the part before it,
        the separator itself, and the part after it. If the separator is not
        found, return S and two empty strings.
        """
        pass

        partition(self,sep)字符串分隔,以字符串sep分隔为前中后三部分,并且以找到的第一个字符为分隔:

        >>> name = '   AlexAesbb   '
      >>> name.partition("x")
      ('   Ale', 'x', 'Aesbb   ')
      >>> name.partition("A")
      ('   ', 'A', 'lexAesbb   ')

        39.replace(self,old,new,count=None)

        def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
        """
        S.replace(old, new[, count]) -> str
            字符串的查找替换
        Return a copy of S with all occurrences of substring
        old replaced by new. If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""
        字符串的替换,old哪个字符要替换,new替换成什么,count替换几个,实例如下:

        >>> name = '   AlexAesbb   '
      >>> name.replace("A","M")
      '   MlexMesbb   '
      >>> name.replace("A","M",1)
      '   MlexAesbb   '

        字符串的查找替换,默认替换全部,可以指定替换的个数。

        39.rfind(self,sub,start=None,end=None)

        def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rfind(sub[, start[, end]]) -> int
            从右侧开始查找
        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end]. Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0

        从字符串右侧开始查找,查找指定字符在字符串中的位置索引:实例如下:

        >>> name = '   AlexAesbb   '
      >>> name.rfind("A")
      7
      >>> name.find("A")
      3
      >>> name.rfind(" ")
      14

        从右侧查找指定字符在字符串中的位置索引,如果查找不到返回-1.

        40.rindex(self,sub,start=None,end=None)

        def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rindex(sub[, start[, end]]) -> int

        Like S.rfind() but raise ValueError when the substring is not found.
        """
        return 0

        rindex(self,sub,start=None,end=None)从字符串右侧查找指定字符的位置索引,如果查找不到就会报错。

        41.rpartition(self,sep)

        def rpartition(self, sep): # real signature unknown; restored from __doc__
        """
        S.rpartition(sep) -> (head, sep, tail)
            从字符串右侧开始查找分隔
        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itself, and the part after it. If the
        separator is not found, return two empty strings and S.
        """
        pass

        rpartition(self,sep)从字符串右侧开始查找分隔,与partition(self,sep)正好相反,示例如下,分隔字符串得到一个元组:

        >>> name = '   AlexAesbb   '
      >>> name.partition("A")
      ('   ', 'A', 'lexAesbb   ')
      >>> name.rpartition("A")
      ('   Alex', 'A', 'esbb   ')

        42.rsplit(self,sep=None,maxsplit=-1)

        def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.rsplit(sep=None, maxsplit=-1) -> list of strings

        Return a list of the words in S, using sep as the
        delimiter string, starting at the end of the string and
        working to the front. If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified, any whitespace string
        is a separator.
        """
        return []

        rsplit(self,sep=None,maxsplit=-1)分隔字符串,并生成一个存放的列表,实例如下:

        >>> name = "Alexsbegcex"
      >>> name.split("e")
      ['Al', 'xsb', 'gc', 'x']
      >>> name.rsplit("e")
      ['Al', 'xsb', 'gc', 'x']

        >>> name.split("e",0)
      ['Alexsbegcex']
      >>> name.split("e",1)
      ['Al', 'xsbegcex']
      >>> name.split("e",2)
      ['Al', 'xsb', 'gcex']
      >>> name.split("e",3)
      ['Al', 'xsb', 'gc', 'x']
      >>> name.split("e",4)
      ['Al', 'xsb', 'gc', 'x']
      >>> name.split("e",-1)
      ['Al', 'xsb', 'gc', 'x']

        以指定字符串分隔,并且替换指定字符,分隔形成一个列表,可以指定分隔字符的个数。

        43.split(self,sep=None,maxsplit=-1)

        def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.split(sep=None, maxsplit=-1) -> list of strings
            分隔字符串,生成一个列表,可以指定分隔的次数,默认是全部分隔
        Return a list of the words in S, using sep as the
        delimiter string. If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are
        removed from the result.
        """
        return []

        44.splitlines(self,keepends=None)

        def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
        """
        S.splitlines([keepends]) -> list of strings

        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []

        splitlines(self,keepends=None)以" "换行符的形式分隔字符串,实例如下:

        >>> user = """
      ... alex
      ... aoi
      ... marry"""

        >>> user.splitlines()
      ['', 'alex', 'aoi', 'marry']

        45.startswith(self,prefix,start=None,end=None)

        def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.startswith(prefix[, start[, end]]) -> bool
            字符串是否以指定字符开始,可以指定起始位置
        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False

        startswith(self,prefix,start=None,end=None)判断字符串是否以指定字符开始,可以指定起始位置,与endswith(self,prefix,start=None,end)

    正好相反,示例如下:

        >>> name = 'Alexsbegcex'
        >>> name.startswith("A")
      True
        >>> name.startswith("w")
      False

        >>> name.startswith("e",2,5)
      True

        46.swapcase(self)

        def swapcase(self): # real signature unknown; restored from __doc__
        """
        S.swapcase() -> str
            将一个字符串中所有大写字符转换为小写,小写转换为大写
        Return a copy of S with uppercase characters converted to lowercase
        and vice versa.
        """
        return ""

        swapcase(self)将一个字符串中所有字符小写转化为大写,大写转化为小写,好贱呀这个方法,实例如下:

        >>> name = 'Alexsbegcex'
      >>> name.swapcase()
      'aLEXSBEGCEX'

        47.title(self)

        def title(self): # real signature unknown; restored from __doc__
        """
        S.title() -> str
            将字符串首字母转换为大写
        Return a titlecased version of S, i.e. words start with title case
        characters, all remaining cased characters have lower case.
        """
        return ""

        48.upper(self)

        def upper(self): # real signature unknown; restored from __doc__
        """
        S.upper() -> str
            将字符串所有字母都转换为大写
        Return a copy of S converted to uppercase.
        """
        return ""

        49.zfill(self,width)

        def zfill(self, width): # real signature unknown; restored from __doc__
        """
        S.zfill(width) -> str
            指定宽度,不足左侧补零
        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width. The string S is never truncated.
        """
        return ""

        zfill(self,width)指定宽度,不足左侧补0,否则不变。实例如下:

        >>> name = 'Alexsbegcex'
      >>> name.zfill(20)
      '000000000Alexsbegcex'
      >>> name.zfill(5)
      'Alexsbegcex'
        50.__contains__(self,*args,**kwargs)

        def __contains__(self, *args, **kwargs): # real signature unknown
        """ Return key in self. """

            判断字符串中是否包含指定字符
        pass

        __contains__(self,*args,**kwargs)判断字符串中是否包含指定字符,实例如下:

        >>> name = 'Alexsbegcex'
      >>> name.__contains__("e")
      True
      >>> name.__contains__("E")
      False























       
     

  • 相关阅读:
    搜索专题
    KMP专题
    CSU 1326: The contest(分组背包)
    强连通专题
    MST:Bad Cowtractors(POJ 2377)
    MST:Agri-Net(POJ 1258)
    ShortestPath:Layout(POJ 3169)(差分约束的应用)
    MST:Conscription(POJ 3723)
    MST:Roadblocks(POJ 3255)
    DP:Space Elevator(POJ 2392)
  • 原文地址:https://www.cnblogs.com/gengcx/p/6750212.html
Copyright © 2011-2022 走看看