1. 程式人生 > >【Python文檔】之str類

【Python文檔】之str類

() abs using xmlchar nat bytes str work ima

文檔

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類