zoukankan      html  css  js  c++  java
  • 我的Python成长之路---第二天---Python基础(7)---2016年1月9日(晴)

    再说字符串

    一、字符串的编码

        字符串的编码是个很令人头疼的问题,由于计算机是美国人发明的,他们很理所当然的认为计算机只要能处理127个字母和一些符号就够用了,所以规定了一个字符占用8个比特(bit)也就是一个字节(byte)来存储字符,也就是ASCII码。

        由于1个字节能表示的最大整数是255,所以处理中文是跟定不行的。鉴于此我们国家制定了了GB2312编码,用来把中文编进去。同样各个国家都有自己的标准来表示本国的文字,比如日本的Shift_JIS,棒子国的Euc-kr。由于各国采用自己的标准,就会不可避免的出现冲突,多语言混合的文本里就出现乱码。

        因此,Unicode应运而生。Unicode第一次把所有国家的语言统一编码。Unicode用两个字节表示一个字符(非常偏僻的字符可能会用到4个字节)。原来ASCII的只需要在前面补零就可以了,例如A的ASCII码是01000001,Unic码就是00000000 01000001。

        但是新问题来了,由于英文字符也占用两个字节,如果一篇文章都是用英文写的,Unicode的要比ASCII多占用1倍的存储空间,非常不划算。

        所以本着节约的原则,可变长编码UTF-8出现了。UTF-8通常用1-6个字节,常用的英文编码还是1个字节,汉子通常3个字节,只有很生僻的字符才会用4-6个字节。我不明白为什么UTF-8三个字节表示中文,如果一篇文章一半英文一半中文,平均下来还是两个字节,更何况如果都是中文的情况,不是反而更占空间了吗。

        三种编码对比:

    二、Python的字符串

        在最新的Python3版本中,字符串是用Unicode表示的,对于单个字符我们可以用Python提供的ord()函数或字符的整数编码(编码的十进制),用chr()吧编码转换为对应的字符

    >>> ord('A')
    65
    >>> ord('')
    24352
    >>> chr(24353)  
    ''

        如果知道字符串的整数编码,可以用十六进制这么表示中文

    >>> 'u4e2du6587'
    '中文'
    >>> '中文'        
    '中文'

        这两种方式是完全等价的。

        由于Python的字符串在内存中用Unicode表示,如果要存储到硬盘或在网络上传输,就需要把字符转化为字节为单位的bytes,Python中用b前缀来表示

    x = b'ABC'

        注意:'ABC'和b'ABC'完全是不一样的,前者是Unicode(占用两个字节)后者是bytes(占用一个字节)

    >>> 'ABC'.encode('ascii') 
    b'ABC'
    >>> 'ABC'.encode('utf-8')
    b'ABC'
    >>> '中文'.encode('utf-8')
    b'xe4xb8xadxe6x96x87'

        可以看出英文既可以用ASCII也可以用Utf-8,而中文只能用Utf-8,参数为通过把字符窜的那种编码转化为bytes(姑且成为字节流吧,不知道正不正确)

        反过来如果想把从网络或磁盘上的字节流转换为Python的字符串,就需要用decode方法

    >>> b'ABC'.decode('ascii')
    'ABC'
    >>> b'ABC'.decode('utf-8')
    'ABC'
    >>> b'xe4xb8xadxe6x96x87'.decode('utf-8')
    '中文'

         关于内置的len方法,如果参数是字符串就统计出字符串的个数,如果是字节流,统计的就是字节数,这点一定要注意

    >>> len(b'xe4xb8xadxe6x96x87')
    6
    >>> len('中文') 
    2

        最后说一下,Python源代码也是一种文本文件,所以我们在保存的时候要保存成UTF-8格式,这还不够,保存成UTF-8只是让操作系统知道是什么格式的文件,Python解释器还不知道。所以要我们要在我们的代码第二行用注释的形式声明是什么格式的文件

    #! /usr/bin/env python3
    # coding=utf-8

       或者

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-

        这两种方式都可以。

    三、字符串的内置方法

        1、capitalize(首字母大写)

        代码:

    1 def capitalize(self): # real signature unknown; restored from __doc__
    2         """
    3         S.capitalize() -> str
    4         # 返回新的字符串对象,首字母大写
    5         Return a capitalized version of S, i.e. make the first character
    6         have upper case and the rest lower case.
    7         """
    8         return ""

        示例:

    >>> str.capitalize()
    'Hello python'

        2、center(居中对齐)

        代码:

     1 def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
     2         """
     3         S.center(width[, fillchar]) -> str
     4         返回新的字符串对象,居中对齐
     5         width:宽度,返回的字符串长度
     6         fillchar:填充字符
     7         Return S centered in a string of length width. Padding is
     8         done using the specified fill character (default is a space)
     9         """
    10         return ""

        示例:

    >>> str.center(25)
    '       hello python      '
    >>> str.center(25, '*')
    '*******hello python******'

        3、count(返回子串出现的次数)

        代码:

     1 def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
     2         """
     3         S.count(sub[, start[, end]]) -> int
     4         # 返回整形,子串出现的次数
     5         sub:查询的子串
     6         start:开始索引
     7         end:结束索引
     8         
     9         Return the number of non-overlapping occurrences of substring sub in
    10         string S[start:end].  Optional arguments start and end are
    11         interpreted as in slice notation.
    12         """
    13         return 0

         示例

    >>> str = 'hello python'
    >>> str.count("o") 
    2
    >>> str.count("o",5)
    1
    >>> str.count("o",5,7)
    0

        4、encode(返回指定编码的字节流)

        代码

     1 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
     2         """
     3         S.encode(encoding='utf-8', errors='strict') -> bytes
     4         返回指定编码的字节流(老师说是uncode编码)
     5         
     6         Encode S using the codec registered for encoding. Default encoding
     7         is 'utf-8'. errors may be given to set a different error
     8         handling scheme. Default is 'strict' meaning that encoding errors raise
     9         a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
    10         'xmlcharrefreplace' as well as any other name registered with
    11         codecs.register_error that can handle UnicodeEncodeErrors.
    12         """
    13         return b""

         示例

    >>> 'ABC'.encode('ascii')
    b'ABC'
    >>> '中文'.encode('utf-8')
    b'xe4xb8xadxe6x96x87'

         5、endswith(判断是否某个子串结尾)

        代码:

     1 def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
     2         """
     3         S.endswith(suffix[, start[, end]]) -> bool
     4         返回布尔值,是否以某个子串结尾
     5         suffix:子串
     6         start:开始索引
     7         end:结束索引
     8         Return True if S ends with the specified suffix, False otherwise.
     9         With optional start, test S beginning at that position.
    10         With optional end, stop comparing S at that position.
    11         suffix can also be a tuple of strings to try.
    12         """
    13         return False

        示例:

    >>> str = 'hello python'    
    >>> str.endswith('thon')
    True
    >>> str[2:8]
    'llo py'
    >>> str.endswith('py', 2, 8)    
    True

        6、expandtabs(设定制表符的宽度)

        代码:

    1 def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
    2         """
    3         S.expandtabs(tabsize=8) -> str
    4         返回新的字符串对象,设定制表符的宽度
    5         Return a copy of S where all tab characters are expanded using spaces.
    6         If tabsize is not given, a tab size of 8 characters is assumed.
    7         """
    8         return ""

        示例

    >>> str = 'hello	python'
    >>> str
    'hello	python'
    >>> print(str)
    hello   python
    >>> print(str.expandtabs())
    hello   python
    >>> print(str.expandtabs(8))
    hello   python
    >>> print(str.expandtabs(16))
    hello           python

         疑惑:这个宽度是单位是什么,8和16也不太成比例

         8、find(查找子串)

         代码

     1 def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
     2         """
     3         S.find(sub[, start[, end]]) -> int
     4         查找子串,返回第一个找到的索引
     5         sub:要查找的子串
     6         start:开始索引
     7         end:结束索引
     8         Return the lowest index in S where substring sub is found,
     9         such that sub is contained within S[start:end].  Optional
    10         arguments start and end are interpreted as in slice notation.
    11         
    12         Return -1 on failure.
    13         找不到返回-1
    14         """
    15         return 0

        示例

    >>> str.find('python')
    6
    >>> str.find('abc')   
    -1

         9、format(格式化输出)

        代码:

    1 def format(*args, **kwargs): # known special case of str.format
    2         """
    3         S.format(*args, **kwargs) -> str
    4         格式化字符串,返回新的字符串对象,类似占位符
    5         
    6         Return a formatted version of S, using substitutions from args and kwargs.
    7         The substitutions are identified by braces ('{' and '}').
    8         """
    9         pass

         示例:

    1 >>> str = "hello {0}"
    2 >>> str.format('python')
    3 'hello python'
    4 >>> str = "hello {0}{1}"    
    5 >>> str.format('python','!')
    6 'hello python!'
    7 >>> str = "hello {name}"    
    8 >>> str.format(name = 'peter')
    9 'hello peter'

        10、format_map(格式化输出)

        代码

    1 def format_map(self, mapping): # real signature unknown; restored from __doc__
    2         """
    3         S.format_map(mapping) -> str
    4         格式化字符串,返回新的字符串对象
    5         mapping:字典对象,用来替换站位符
    6         Return a formatted version of S, using substitutions from mapping.
    7         The substitutions are identified by braces ('{' and '}').
    8         """
    9         return ""

         示例

    >>> str = "hello {name}"      
    >>> str.format_map({"name":"peter"})
    'hello peter'

        11、index(查找子串,返回子串的索引)

        代码:

    1 def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
    2         """
    3         S.index(sub[, start[, end]]) -> int
    4         查找子串,使用方法同find,不同是如果不存在会报错
    5         Like S.find() but raise ValueError when the substring is not found.
    6         """
    7         return 0

         示例:

    >>> str = 'hello python'               
    >>> str.index('python')
    6
    >>> str.index('abc')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: substring not found

        12、isalnum(判断字符串是否有字母和数字组成)

        代码:

    1 def isalnum(self): # real signature unknown; restored from __doc__
    2         """
    3         S.isalnum() -> bool
    4         判断是否为数字和字母组成
    5         Return True if all characters in S are alphanumeric
    6         and there is at least one character in S, False otherwise.
    7         """
    8         return False

        示例

    >>> str = 'hello python'
    >>> str.isalnum()
    False
    >>> str = 'hellopython' 
    >>> str.isalnum()      
    True
    >>> str = 'hellopython345'
    >>> str = 'hello python3.4'
    >>> str.isalnum()
    False

         13、isalpha(判断字符串是否全有字母组成)

        代码:

    1 def isalpha(self): # real signature unknown; restored from __doc__
    2         """
    3         S.isalpha() -> bool
    4         判断是否全部全由字母组成
    5         Return True if all characters in S are alphabetic
    6         and there is at least one character in S, False otherwise.
    7         """
    8         return False

        示例:

    >>> str.isalnum()
    False
    >>> str = 'hellopython345' 
    >>> str.isal
    str.isalnum(  str.isalpha(  
    >>> str.isalpha()
    False
    >>> str = 'hellopython'   
    >>> str.isalpha()      
    True
    >>> str = 'hello python'
    >>> str.isalpha()       
    False

        14、isdecimal(判断是否由十进制数组成,相当于由[0-9]组成)

        代码:

    1 def isdecimal(self): # real signature unknown; restored from __doc__
    2         """
    3         S.isdecimal() -> bool
    4         判断是否由十进制数字组成
    5         Return True if there are only  characters in S,
    6         False otherwise.
    7         """
    8         return False

        示例:

    >>> str = "10"     
    >>> str.isdecimal()
    True
    >>> str = "10.1"   
    >>> str.isdecimal()
    False

        15、isdigit(判断是否由数字组成,同上)

        代码:

    1 def isdigit(self): # real signature unknown; restored from __doc__
    2         """
    3         S.isdigit() -> bool
    4         判断是否由数字组成
    5         Return True if all characters in S are digits
    6         and there is at least one character in S, False otherwise.
    7         """
    8         return False

        示例:

    >>> str = "123"
    >>> str.isdigit()
    True
    >>> str = "12.3" 
    >>> str.isdigit()
    False

        16、ididentifier(返回是否合法标识符,也就是是否符合python变量名语法)

        代码:

     1 def isidentifier(self): # real signature unknown; restored from __doc__
     2         """
     3         S.isidentifier() -> bool
     4         返回是否为合法表示符(是否符合python变量名语法,但是不搞包括是否是python保留的关键字)
     5         Return True if S is a valid identifier according
     6         to the language definition.
     7         
     8         Use keyword.iskeyword() to test for reserved identifiers
     9         such as "def" and "class".
    10         """
    11         return False

        示例:

    >>> str = "p1"        
    >>> str.isidentifier()
    True
    >>> str = "1p"        
    >>> str.isidentifier()
    False
    >>> str = "__pp"      
    >>> str.isidentifier()
    True
    >>> str = "def" # python关键字,一样是合法的
    >>> str.isidentifier()
    True

        17、islower(判断字符是否是小写字符)

        代码:

    1 def islower(self): # real signature unknown; restored from __doc__
    2         """
    3         S.islower() -> bool
    4         判断字符是否全为小写(只判断字母,数字符号被忽略)
    5         Return True if all cased characters in S are lowercase and there is
    6         at least one cased character in S, False otherwise.
    7         """
    8         return False

        示例:

    >>> str = "hello python"
    >>> str.islower()
    True
    >>> str = "hello python123"
    >>> str.islower()   # 数字和空格等符号被忽略
    True

        18、isnumeric(判断是否由数字组成)

        代码:

    1 def isnumeric(self): # real signature unknown; restored from __doc__
    2         """
    3         S.isnumeric() -> bool
    4         判断是否由数字组成
    5         Return True if there are only numeric characters in S,
    6         False otherwise.
    7         """
    8         return False

        示例:

    >>> str = "12.3"           
    >>> str.isnumeric()
    False
    >>> str = "12a"    
    >>> str.isnumeric()
    False
    >>> str = "-1"     
    >>> str.isnumeric()
    False
    >>> str = "123"    
    >>> str.isnumeric()
    True

        19、isprintable(判断是否由可打印字符组成)

        代码:

    def isprintable(self): # real signature unknown; restored from __doc__
            """
            S.isprintable() -> bool
            判断是会否由可打印字符组成
            Return True if all characters in S are considered
            printable in repr() or S is empty, False otherwise.
            """
            return False

        示例:

    >>> str = "123"    
    >>> str.isprintable()
    True
    >>> str = "123	"    
    >>> str.isprintable()
    False
    >>> str = "123\"    
    >>> str.isprintable()
    True
    >>> str = "123%s"    
    >>> str.isprintable()
    True
    >>> str = "123
    "    
    >>> str.isprintable()
    False

        20、isspace(是否由空字符组成:空格、tab、回车)

        代码:

    1 def isspace(self): # real signature unknown; restored from __doc__
    2         """
    3         S.isspace() -> bool
    4         判断是否为空字符组成空格、tab、回车
    5         Return True if all characters in S are whitespace
    6         and there is at least one character in S, False otherwise.
    7         """
    8         return False

        示例:

    >>> str = ""         
    >>> str.isspace()
    False
    >>> str = " "    
    >>> str.isspace()
    True
    >>> str = "	"   
    >>> str.isspace()
    True
    >>> str = "hello python"
    >>> str.isspace()
    False
    >>> str = "
    "
    >>> str.isspace()
    True

        21、istitle(判断是否是标题格式)

        代码:

     1 def istitle(self): # real signature unknown; restored from __doc__
     2         """
     3         S.istitle() -> bool
     4         判断是否是标题格式(单词首字母大写)
     5         Return True if S is a titlecased string and there is at least one
     6         character in S, i.e. upper- and titlecase characters may only
     7         follow uncased characters and lowercase characters only cased ones.
     8         Return False otherwise.
     9         """
    10         return False

        示例:

    >>> str = "Hello Python"
    >>> str.istitle()
    True
    >>> str = "Hello python"
    >>> str.istitle()       
    False

         22、isupper(判断是否是大写)

        代码:

    1 def isupper(self): # real signature unknown; restored from __doc__
    2         """
    3         S.isupper() -> bool
    4         判断字符是否为大写
    5         Return True if all cased characters in S are uppercase and there is
    6         at least one cased character in S, False otherwise.
    7         """
    8         return False

        示例:

    >>> str = "HELLO PYTHON"
    >>> str.isupper()
    True
    >>> str = "HELLO PYTHOn"
    >>> str.isupper()       
    False

        23、join(拼接序列)

        代码:

    1 def join(self, iterable): # real signature unknown; restored from __doc__
    2         """
    3         S.join(iterable) -> str
    4         以当前字符串为分隔符,拼接序列对象(如列表、元祖等),返回新的字符串对象
    5         iterable:要拼接的序列化对象
    6         Return a string which is the concatenation of the strings in the
    7         iterable.  The separator between elements is S.
    8         """
    9         return ""

        示例:

    >>> li = ['hello','python']
    >>> ' '.join(li)
    'hello python'

        24、ljust(左对齐)
        代码:

     1 def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
     2         """
     3         S.ljust(width[, fillchar]) -> str
     4         左对齐,返回新的字符串对象
     5         width:新出的字符串对象宽度
     6         fillchar:填充字符串,默认是空格
     7         Return S left-justified in a Unicode string of length width. Padding is
     8         done using the specified fill character (default is a space).
     9         """
    10         return ""

        示例:

    >>> str = "Python"
    >>> str.ljust(15)
    'Python         '
    >>> str.ljust(15,'*')
    'Python*********'

        25、lower(字符串小写)

        代码:

    1 def lower(self): # real signature unknown; restored from __doc__
    2         """
    3         S.lower() -> str
    4         返回小写
    5         Return a copy of the string S converted to lowercase.
    6         """
    7         return ""

        示例:

    >>> str = "PythoN"
    >>> str.lower()   
    'python'

        26、lstrip(脱去左侧的空格或自定子串)

        代码:

    1 def lstrip(self, chars=None): # real signature unknown; restored from __doc__
    2         """
    3         S.lstrip([chars]) -> str
    4         脱去左侧的空格或自定子串
    5         chars:要脱去的子串
    6         Return a copy of the string S with leading whitespace removed.
    7         If chars is given and not None, remove characters in chars instead.
    8         """
    9         return ""

        示例:

    >>> str = "   Python"
    >>> str.lstrip()
    'Python'
    >>> str = "Python"   
    >>> str.lstrip("Py")
    'thon'

        27、maketrans和translate

        代码

     1 def maketrans(self, *args, **kwargs): # real signature unknown
     2         """
     3         Return a translation table usable for str.translate().
     4         创建translate对照表
     5         If there is only one argument, it must be a dictionary mapping Unicode
     6         ordinals (integers) or characters to Unicode ordinals, strings or None.
     7         Character keys will be then converted to ordinals.
     8         If there are two arguments, they must be strings of equal length, and
     9         in the resulting dictionary, each character in x will be mapped to the
    10         character at the same position in y. If there is a third argument, it
    11         must be a string, whose characters will be mapped to None in the result.
    12         """
    13         pass

        

    def translate(self, table): # real signature unknown; restored from __doc__
            """
            S.translate(table) -> str
            通过对照表完成字符替换
            table:对照表对象,maketrans返回的对象
            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 ""

        示例:

    >>> trantab = str.maketrans('123', 'abc')
    >>> s = ('123456')
    >>> s.translate(trantab)
    'abc456'

        28、partition(返回分隔符分隔的元祖,从左侧开始查找)

        代码:

     1 def partition(self, sep): # real signature unknown; restored from __doc__
     2         """
     3         S.partition(sep) -> (head, sep, tail)
     4         返回一个三个元素的元祖,第一个元素为分隔符左侧的子串,第二个元素为分隔符,第三个元素为分隔符右侧的子串
     5         sep:分隔符
     6 
     7         Search for the separator sep in S, and return the part before it,
     8         the separator itself, and the part after it.  If the separator is not
     9         found, return S and two empty strings.
    10         """
    11         pass

        示例:

    >>> str = "http://www.baidu.com"
    >>> str.partition("//")
    ('http:', '//', 'www.baidu.com')

         29、replace(子串替换)

        代码:

     1 def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
     2         """
     3         S.replace(old, new[, count]) -> str
     4         子串替换
     5         old:旧的子串
     6         new:新的子串
     7         count:替换的次数
     8         Return a copy of S with all occurrences of substring
     9         old replaced by new.  If the optional argument count is
    10         given, only the first count occurrences are replaced.
    11         """
    12         return ""

        示例:

    >>> str = "abcadd"
    >>> str.replace("a","1")
    '1bc1dd'
    >>> str.replace("a","1", 1)
    '1bcadd'

        30、rfind(从右查找子串)

    def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.rfind(sub[, start[, end]]) -> int
            从右查找子串,返回索引,找不到返回-1
            sub:查找的子串
            strat:开始索引
            end:结束所以你能
    
            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

         31、rindex(从右查找子串)

         代码:

     1 def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
     2         """
     3         S.rfind(sub[, start[, end]]) -> int
     4         从右查找子串,返回索引
     5         sub:查找的子串
     6         strat:开始索引
     7         end:结束所以你能
     8 
     9         Return the highest index in S where substring sub is found,
    10         such that sub is contained within S[start:end].  Optional
    11         arguments start and end are interpreted as in slice notation.
    12         
    13         Return -1 on failure.
    14         """
    15         return 0

          32、rjust(右对齐)

         代码:

     1 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
     2         """
     3         S.rjust(width[, fillchar]) -> str
     4         右对齐
     5         width:宽度
     6         fillchar:填充字符
     7         Return S right-justified in a string of length width. Padding is
     8         done using the specified fill character (default is a space).
     9         """
    10         return ""

        33、rpartition(返回分隔符分隔的元祖,从右侧开始查找)

        代码:

     1 def rpartition(self, sep): # real signature unknown; restored from __doc__
     2         """
     3         S.rpartition(sep) -> (head, sep, tail)
     4         返回一个三个元素的元祖,第一个元素为分隔符左侧的子串,第二个元素为分隔符,第三个元素为分隔符右侧的子串
     5         sep:分隔符
     6         Search for the separator sep in S, starting at the end of S, and return
     7         the part before it, the separator itself, and the part after it.  If the
     8         separator is not found, return two empty strings and S.
     9         """
    10         pass

        34、rsplit(分隔字符串,从右侧开始分隔)

        代码:

     1 def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
     2         """
     3         S.rsplit(sep=None, maxsplit=-1) -> list of strings
     4         返回将字符串以指定分隔符分隔的列表,从右边开始查找分隔符
     5         sep:分隔符
     6         maxsplit:最多分隔的次数
     7         Return a list of the words in S, using sep as the
     8         delimiter string, starting at the end of the string and
     9         working to the front.  If maxsplit is given, at most maxsplit
    10         splits are done. If sep is not specified, any whitespace string
    11         is a separator.
    12         """
    13         return []

        示例:

    >>> str = "hello python nihao"
    >>> str.rsplit(maxsplit = 1)  
    ['hello python', 'nihao']
    >>> str.rsplit()            
    ['hello', 'python', 'nihao']

        35、rstrip(脱去右边的空格或自定义字符串)

        代码:

    1 def rstrip(self, chars=None): # real signature unknown; restored from __doc__
    2         """
    3         S.rstrip([chars]) -> str
    4         脱去右边的空格或自定义字符串
    5         chars:欲脱去的字符串或字符
    6         Return a copy of the string S with trailing whitespace removed.
    7         If chars is given and not None, remove characters in chars instead.
    8         """
    9         return ""

        36、split(分隔字符串,从左侧开始)

        代码:

    def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
            """
            S.split(sep=None, maxsplit=-1) -> list of strings
            分隔字符串
            sep:分隔符
            maxsplit:最多分隔的次数
            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 []

        37、splitlines(以换行符为分隔符分隔字符串)

        代码:

    def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
            """
            S.splitlines([keepends]) -> list of strings
            以换行符为分隔符分隔字符串
            keepends:是否保留换行符
            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 []

        示例:

    >>> str = "hello
    python
    nihao
    "
    >>> str.splitlines()
    ['hello', 'python', 'nihao']
    >>> str.splitlines(True)
    ['hello
    ', 'python
    ', 'nihao
    ']

         38、startswith(以某个子串开头)

        代码:

    def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.startswith(prefix[, start[, end]]) -> bool
            返回布尔值,是否以某个子串开头
            prefix:前缀也就是要查找的子串
            start:开始索引
            end:结束索引
            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

        示例:

    >>> str = 'Python'
    >>> str.startswith('Py')
    True
    >>> str.startswith('Py',2)  
    False

         39、strip(脱去两边的空格或自定义字符)

        代码:

     1 def strip(self, chars=None): # real signature unknown; restored from __doc__
     2         """
     3         S.strip([chars]) -> str
     4         脱去两边的空格或自定义字符
     5         chars:欲脱去的字符串或字符
     6         Return a copy of the string S with leading and trailing
     7         whitespace removed.
     8         If chars is given and not None, remove characters in chars instead.
     9         """
    10         return ""

        示例:

    >>> str = '  Python  '    
    >>> str.strip()
    'Python'
    >>> str = '***python**'
    >>> str.strip('*')
    'python'

        40、swapcase(大小写交换)

        代码:

    1 def swapcase(self): # real signature unknown; restored from __doc__
    2         """
    3         S.swapcase() -> str
    4         大小写交换
    5         Return a copy of S with uppercase characters converted to lowercase
    6         and vice versa.
    7         """
    8         return ""

        示例:

    >>> str = 'PythoN'     
    >>> str.swapcase()
    'pYTHOn'

        41、title(将字符串转为标题格式、每个单词首字母大写)

        代码:

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

        示例:

    >>> str = 'hello python' 
    >>> str.title()
    'Hello Python'

        42、upper(将字母转为大写)

        代码:

    1 def upper(self): # real signature unknown; restored from __doc__
    2         """
    3         S.upper() -> str
    4         将字母转化为大写
    5         Return a copy of S converted to uppercase.
    6         """
    7         return ""

       示例:

    >>> str = 'Hello Python'
    >>> str.upper()
    'HELLO PYTHON'

        43、zfill(右对齐,以字符0填充)

        代码:

    1 def zfill(self, width): # real signature unknown; restored from __doc__
    2         """
    3         S.zfill(width) -> str
    4         右对齐,以字符0填充
    5         width:宽度
    6         Pad a numeric string S with zeros on the left, to fill a field
    7         of the specified width. The string S is never truncated.
    8         """
    9         return ""

       示例:

    >>> str = 'Python'      
    >>> str.zfill(10)
    '0000Python'
  • 相关阅读:
    hdu 2191 珍惜现在,感恩生活(多重背包)
    《从Paxos到ZooKeeper分布式一致性原理与实践》学习知识导图
    你对ArrayList了解多少?
    JAVA酒店管理系统
    C#酒店管理系统
    C#图书管理系统
    java图书管理系统
    豆瓣高分JAVA书籍,你都读过吗?
    JAVA课程设计----------JAVA学生信息管理系统
    C#学生管理系统
  • 原文地址:https://www.cnblogs.com/zhangxiaxuan/p/5105743.html
Copyright © 2011-2022 走看看