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

【Python文档】之str类

时间:2018-03-22 00:25:14      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:nic   而且   调用   判断   不同   begin   empty   placed   字符串替换   

文档

class str(object):
    """
    str(object=‘‘) -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str
    ---------------------------------------------------------------------
    Create a new string object from the given object. If encoding or
    errors is specified, then the object must expose a data buffer
    that will be decoded using the given encoding and error handler.
    Otherwise, returns the result of object.__str__() (if defined)
    or repr(object).
    将一个指定的对象转换为字符串形式,几根据一个指定的对象创建一个新的字符串对象。
    另外,str(object)可以返回一个对象的信息说明,
    如果没有,则会调用object对象的__str__()方法
    如:print(str(print))的结果为:<built-in function print>
    ---------------------------------------------------------------------
    encoding defaults to sys.getdefaultencoding().
    errors defaults to ‘strict‘.
    """

    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.
        将一个字符串首字母转换为大写,而且!而且其余字母全部转换为小写
        如:‘fuyong‘.capitalize()与print(‘fuyong‘.capitalize()的结果均为‘Fuyong‘
        ---------------------------------------------------------------------
        """
        return ""


    def center(self, width, fillchar=None):  # real signature unknown; restored from __doc__
        """
        S.center(width[, fillchar]) -> str
        ---------------------------------------------------------------------
        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        将字符串居中显示,可以指定总宽度以及填充值,默认用空格填充
        如:print(‘fuyong‘.center(20,‘*‘))的结果为:‘*******fuyong*******‘
        ---------------------------------------------------------------------
        """
        return ""

    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.
        返回一个子字符串在该字符串中出现的次数。参数start和end是可选参数,可以理解为是一个切片
        ---------------------------------------------------------------------
        print(‘fuxiaoyong‘.count(‘o‘))      # 2
        print(‘fuxiaoyong‘.count(‘o‘,6))    # 1
        print(‘fuxiaoyong‘.count(‘o‘,6,8))  # 1
        ---------------------------------------------------------------------
        """
        return 0

    def encode(self, encoding=‘utf-8‘, errors=‘strict‘):  # real signature unknown; restored from __doc__
        """
        S.encode(encoding=‘utf-8‘, errors=‘strict‘) -> bytes
        将一个字符串按照指定的编码方式编码成bytes类型,默认的编码格式为utf-8
        ---------------------------------------------------------------------
        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""

    def endswith(self, suffix, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.endswith(suffix[, start[, end]]) -> bool
        判断一个字符串是否以一个指定后缀结尾,返回一个布尔值
        ---------------------------------------------------------------------
        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.
        如果是以指定的后缀结尾,则返回True,否则返回False
        start和end参数是可选参数。可以指定起始位置与结束位置,在此范围内进行判断,类似于切片的方式
        后缀也可以是一个元组或者字符串,
        如果是一个元组的话,后缀就在元组里选,任意一个元素满足返回True
        ---------------------------------------------------------------------
        print(‘fuyong‘.endswith(‘g‘))          # True
        print(‘fuyong‘.endswith(‘ong‘))        # True
        print(‘fuyong‘.endswith(‘ong‘,2))      # True
        print(‘fuyong‘.endswith(‘ong‘,1,3))    # False
        print(‘fuyong‘.endswith((‘n‘,‘g‘)))    # True
        print(‘fuyong‘.endswith((‘n‘,‘m‘)))    # False
        ---------------------------------------------------------------------
        """
        return False

    def expandtabs(self, tabsize=8):  # real signature unknown; restored from __doc__
        """
        S.expandtabs(tabsize=8) -> str

        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.
        如果一个字符串中包括制表符‘\t‘,那么可以用tabsize参数指定制表符的长度,
        tabsize是可选的,默认值是8个字节
        ---------------------------------------------------------------------
        print(‘fu\tyong‘.expandtabs())      # ‘fu      yong‘
        print(‘fu\tyong‘.expandtabs(4))     # ‘fu  yong‘
        ---------------------------------------------------------------------
        """
        return ""

    def find(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.find(sub[, start[, end]]) -> int
        查找一个子字符串在原字符串中的位置,返回一个int类型的索引值
        ---------------------------------------------------------------------
        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.
        如果在其中能找到(一个或多个)指定字符串,则返回最小索引值的那一个
        意思是从左往右找,返回找到的第一个的索引值
        也可以通过可选参数start和end来指定查找范围
        ---------------------------------------------------------------------
        Return -1 on failure.
        如果找不到,则返回 -1
        ---------------------------------------------------------------------
        print(‘fuyong‘.find(‘o‘))                     # 3
        print(‘fuyong is a old man‘.find(‘o‘))        # 3
        print(‘fuyong is a old man‘.find(‘o‘,8))      # 12
        print(‘fuyong is a old man‘.find(‘o‘,5,8))    # -1
        ---------------------------------------------------------------------
        """
        return 0

    def format(self, *args, **kwargs):  # known special case of str.format
        """
        S.format(*args, **kwargs) -> str
        格式化输出,返回一个str
        ---------------------------------------------------------------------
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces (‘{‘ and ‘}‘).
        格式化输出一段字符串。用{}的形式来占位
        ---------------------------------------------------------------------
        =根据位置一一填充=
        print(‘{}今年{}岁,{}是一个春心荡漾的年纪‘.format(‘fuyong‘,18,18))

        =根据索引对应填充=
        print(‘{0}今年{1}岁,{1}是一个春心荡漾的年纪‘.format(‘fuyong‘,18))

        =根据关键字对应填充=
        print(‘{name}今年{age}岁,{age}是一个春心荡漾的年纪‘.format(name=‘fuyong‘,age=18))

        =根据列表的索引填充=
        num_list = [3,2,1]
        print(‘列表的第二个数字是{lst[1]},第三个数字是{lst[2]}‘.format(lst=num_list))

        =根据字典的key填充=
        info_dict = {‘name‘:‘fuyong‘,‘age‘:18}
        print("他的姓名是{dic[name]},年纪是{dic[age]}".format(dic=info_dict))

        =根据对象的属性名填充=
        class Person:
            def __init__(self,name,age):
                self.name = name
                self.age = age
        print("他的姓名是{p.name},年纪是{p.age}".format(p=Person(‘fuyong‘,18)))
        ---------------------------------------------------------------------
        """
        pass

    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.
        跟find()函数类似,不同的是,如果找不到则会直接报错
        ---------------------------------------------------------------------
        """
        return 0

    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

    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

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

        Return True if there are only decimal characters in S,
        False otherwise.
        判断一个字符串是不是全部由十进制字符组成,返回一个布尔值
        """
        return False

    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


    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.
        判断一个字符串是否全部由小写字母组成,如果有任意一个字符为大写,则返回False
        """
        return False

    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

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

        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

    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.
        判断一个字符串是否全部由大写字母组成,如果有任意一个字符为小写,则返回False
        """
        return False

    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 ""

    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).
        以左为齐,将一个字符串的右!!右边填充指定字符串,可以指定宽度,默认为用空格填充。
        不会改变原字符串,而会重新生成一个字符串

        print(‘fuyong‘.ljust(10,‘*‘))  # fuyong****
        """
        return ""

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

        Return a copy of the string S converted to lowercase.
        将一个字符串中的字符全部变为小写
        """
        return ""

    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 ""

    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.
        将字符串中的某一个子字符串替换为指定字符串
        print(‘fuyong‘.replace(‘yong‘,‘sir‘))  #fusir
        """
        return ""

    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.
        与find方法类似,但是是从右边开始查找

        Return -1 on failure.
        如果找不到则返回 -1
        """
        return 0

    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.
        与index方法类似,但是是从右边开始查找
        如果找不到会直接报错
        """
        return 0

    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).
        以右为齐,将一个字符串的左!!左边填充指定字符串,可以指定宽度,默认为用空格填充。
        print(‘fuyong‘.rjust(10,‘*‘))  # ****fuyong
        """
        return ""

    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 []

    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 ""

    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.
        将一个字符串以指定的子字符串进行分割,返回一个列表
        如果找不到指定的子字符串,则会将原字符串直接放到一个列表中

        print(‘fu.yong‘.split(‘.‘))     # [‘fu‘, ‘yong‘]
        print(‘fu.yong‘.split(‘*‘))     # [‘fu.yong‘]
        """
        return []



    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.

        如果是以指定的字符串结尾,则返回True,否则返回False
        start和end参数是可选参数。可以指定起始位置与结束位置,在此范围内进行判断,类似于切片的方式
        后缀也可以是一个元组或者字符串,
        如果是一个元组的话,后缀就在元组里选,任意一个元素满足返回True
        """
        return False

    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 ""

    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.
        将一个字符串的大小写反转
        print(‘u.Yong‘.swapcase())  # fU.yONG
        """
        return ""

    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.
        将一个字符串的!每个单词!首字母大写,并且,其他字母小写
        注意与capitalize的却别
        ---------------------------------------------------------------------
        print(‘fuYong‘.capitalize())    #Fuyong
        print(‘fu Yong‘.capitalize())   #Fu yong
        ---------------------------------------------------------------------
        print(‘fuYONG‘.title())         # Fuyong
        print(‘fu YONG‘.title())        #Fu Yong
        """
        return ""


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

        Return a copy of S converted to uppercase.
        将一个字符串的全部字符大写
        """
        return ""

    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.
        将一个字符串按照指定宽度在左侧用0填充
        注意,只填充左侧,而且只能用0填充
        ---------------------------------------------------------------------
        print(‘fuyong‘.zfill(10))   #0000fuyong
        """
        return ""

  

示例

print(‘fuyong‘.capitalize())
print(‘fuyong‘.capitalize())

print(‘fuyong‘.center(20,‘*‘))

print(‘fuxiaoyong‘.count(‘o‘))
print(‘fuxiaoyong‘.count(‘o‘,6))
print(‘fuxiaoyong‘.count(‘o‘,6,8))

print(‘fuyong‘.endswith(‘ong‘))
print(‘fuyong‘.endswith(‘ong‘,2))
print(‘fuyong‘.endswith(‘ong‘,1,3))
print(‘fuyong‘.endswith((‘n‘,‘g‘)))
print(‘fuyong‘.endswith((‘n‘,‘g‘)))
print(‘fuyong‘.endswith((‘n‘,‘m‘)))

print(‘fu\tyong‘.expandtabs())
print(‘fu\tyong‘.expandtabs(4))

print(‘fuyong‘.find(‘o‘))
print(‘fuyong is a old man‘.find(‘o‘))
print(‘fuyong is a old man‘.find(‘o‘,8))
print(‘fuyong is a old man‘.find(‘o‘,5,8))

print(‘{}今年{}岁,{}是一个春心荡漾的年纪‘.format(‘fuyong‘,18,18))
print(‘{0}今年{1}岁,{1}是一个春心荡漾的年纪‘.format(‘fuyong‘,18))
print(‘{name}今年{age}岁,{age}是一个春心荡漾的年纪‘.format(name=‘fuyong‘,age=18))

num_list = [3,2,1]
print(‘列表的第二个数字是{lst[1]},第三个数字是{lst[2]}‘.format(lst=num_list))

info_dict = {‘name‘:‘fuyong‘,‘age‘:18}
print("他的姓名是{dic[name]},年纪是{dic[age]}".format(dic=info_dict))

class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
print("他的姓名是{p.name},年纪是{p.age}".format(p=Person(‘fuyong‘,18)))

print(‘11‘.isdecimal())

print(‘fuyong‘.rjust(10,‘*‘))

print(‘fuyong‘.replace(‘yong‘,‘sir‘))

print(‘fu.yong‘.split(‘.‘))
print(‘fu.yong‘.split(‘*‘))

print(‘fu.Yong‘.swapcase())

print(‘fuYong‘.capitalize())
print(‘fu Yong‘.capitalize())

print(‘fuYONG‘.title())
print(‘fu YONG‘.title())

print(‘fuyong‘.zfill(10))

  

【Python文档】之str类

标签:nic   而且   调用   判断   不同   begin   empty   placed   字符串替换   

原文地址:https://www.cnblogs.com/fu-yong/p/8620730.html

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