python基础(10)-匿名函数&内置函数

时间:2023-03-09 00:16:01
python基础(10)-匿名函数&内置函数

匿名函数

例子

  • 返回两个数的和

     def add(x, y):
         return x + y
    
     # 等价于
    
     add = lambda x, y: x + y
     
  • 返回字典中值最大的key

     dic = {'a': 13, 'b': 3, 'c': 34}
     print(max(dic,key=lambda x:dic[x]))

面试题

  • 题1

    现有两元组(('a'),('b')),(('c'),('d')), 请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]

     ret = zip((('a'),('b')),(('c'),('d')))
     res = map(lambda tup:{tup[0]:tup[1]},ret)
     print(list(res))
  • 题2

    写出下列代码输出结果

     def multipliers():
         return [lambda x: i * x for i in range(4)]
     # 返回3个匿名函数,到执行时i的值已为3
     print([m(2) for m in multipliers()])
     # result:
     # [6, 6, 6, 6]

内置函数

数字相关

  • 数据类型转换

    • bool()

      转布尔类型

       print(bool([]))  # False
       print(bool(''))  # False
       print(bool(0))  # False
       print(bool({}))  # False
       print(bool(()))  # False
    • int()

      转整形

       
    • float()

      转浮点型

       '))  # 3.0
    • complex()

      转复数类型

       '))  # (3+0j)
  • 进制转换

    • bin()

      转二进制

       print(bin(2))  # 0b10
    • oct()

      转八进制

       print(oct(2))  # 0o2
    • hex()

      转十六进制

       print(hex(2))  # 0x2
  • 数学运算

    • abs()

      绝对值

       
    • divmod()

      除余

       print(divmod(9, 4))  # (2, 1)  商2余1
    • round()

      精确小数位

       print(round(3.5687789,3))  # 3.569
    • pow()

      幂运算

       
    • sum()

      求和

       
    • max()

      最大值

       
    • min()

      最小值

       

数据结构相关

  • 类型转换

    • list()

      转列表类型

       print(list((1,2,3)))  # [1, 2, 3]
    • tuple()

      转元组类型

       print(tuple([1,2,3]))  # (1, 2, 3)
    • dict()

      转字典类型

       print(dict({1:'a',2:'b'}))  # {1: 'a', 2: 'b'}
    • set()

      转集合类型

       print(set([1,1,2,3,3]))  # {1, 2, 3}
    • frozenset()

      转不可变集合类型

       only_read_set = frozenset([1, 1, 2, 3, 3]);
       print(only_read_set)  # frozenset({1, 2, 3})
       only_read_set[1] = 4  # TypeError: 'frozenset' object does not support item assignment
  • 字符串相关

    • str()

      转字符串

       
    • format()

      1.将一个数值进行格式化显示

      2.如果参数format_spec未提供,则和调用str()效果相同

      3.对于不同的类型,参数format_spec可提供的值都不一样

       print(format(3.1415926))  # 3.1415926
       # 字符串:指定对齐方式,<是左对齐, >是右对齐,^是居中对齐
       print(format('format', '<20'))
       print(format('format', '>20'))
       print(format('format', '^20'))
       # result:
       # format
       #               format
       #        format
      
       # 整形:
       # 转换成二进制
      
       # 转换unicode成字符
       print(format(97, 'c'))  # a
       # 转换成10进制
      
       # 转换成8进制
      
       # 转换成16进制 小写字母表示
       print(format(11, 'x'))  # b
       # 转换成16进制 大写字母表示
       print(format(11, 'X'))  # B
       # 和d一样
      
       # 默认和d一样
      
       # 浮点型:
       # 科学计数法,默认保留6位小数
       print(format(314159267, 'e'))  # '3.141593e+08'
       # 科学计数法,指定保留2位小数
       print(format(314159267, '0.2e'))  # '3.14e+08'
       # 科学计数法,指定保留2位小数,采用大写E表示
       print(format(314159267, '0.2E'))  # '3.14E+08'
       # 小数点计数法,默认保留6位小数
       print(format(314159267, 'f'))  # '314159267.000000'
       # 小数点计数法,默认保留6位小数
       print(format(3.14159267000, 'f'))  # '3.141593'
       ##小数点计数法,指定保留8位小数
       print(format(3.14159267000, '0.8f'))  # '3.14159267'
       # 小数点计数法,指定保留10位小数
       print(format(3.14159267000, '0.10f'))  # '3.1415926700'
       # 小数点计数法,无穷大转换成大小字母
       print(format(3.14e+1000000, 'F'))  # 'INF'
    • bytes()

      转字节

       print(bytes('aaa', 'utf8'))  # b'aaa'
       print('aaa'.encode('utf8'))  # b'aaa'
    • bytearray()

      转字节数组

       print(bytearray('aaa', 'utf8'))  # bytearray(b'aaa')
       for i in bytearray('aaa', 'utf8'):
           print(i)
      
    • memoryview()

      查看bytes内存地址

       print(memoryview(bytes('a', 'utf8')))  # <memory at 0x000000000272A588>
    • ord()

      字符按unicode转数字

       
    • chr()

      数字按unicode转字符

       print(chr(97))  # 'a'
    • ascii()

      转ascii码

       # 只要是ascii码中的内容,就原样输出,不是就转换成\u格式
       print(ascii('张三'))  # '\u5f20\u4e09'
    • repr()

      将一个对象以字符串形式返回

       print('hello%r' % 'world')  # hello'world'
       '))  # '1'
       print(repr([1, 2, 3]))  # [1, 2, 3]
  • 相关内置函数

    • len()

      返回可迭代对象长度

      
      
    • enumerate()

      枚举化

       print(list(enumerate(['a', 'b', 'c'])))  # [(0, 'a'), (1, 'b'), (2, 'c')]
    • all()

      所有值都为True则返回True,否则返回False

       print(all([True, '', 1]))  # False
    • any()

      存在一个值为True则返回True,否则返回False

       print(any([True, False, 0, '']))  # True
    • zip()

      拉链方法,返回一个迭代器

       num_list = [1, 2, 3]
       letter_list = ['a', 'b', 'c']
       print(zip(num_list, letter_list))  # <zip object at 0x00000000021DB648>
       print(list(zip(num_list, letter_list)))  # [(1, 'a'), (2, 'b'), (3, 'c')]
    • filter()

      过滤

       # 筛选num_list里的奇数
       num_list = [1, 2, 3, 4, 5, 6]
       result_list = filter(lambda i: i % 2 == 1, num_list)
       print(list(result_list))  # [1, 3, 5]
       # 等价于
       print(list(i for i in num_list if i % 2 == 1))  # [1, 3, 5]
    • map()

      映射

       # 取列表中每个数的平方
       num_list = [1, 2, 3, 4, 5, 6]
       print(list(map(lambda i: i ** 2, num_list)))  # [1, 4, 9, 16, 25, 36]
    • sorted()

      排序

       num_list = [-1, -2, 3, -4]
       # 默认排序
       print(sorted(num_list))  # [-4, -2, -1, 3]
       # 以列表中数字的绝对值升序
       print(sorted(num_list, key=abs))  # [-1, -2, 3, -4]
       # 以列表中数字的绝对值降序
       print(sorted(num_list, key=abs, reverse=True))  # [-4, 3, -2, -1]

面向对象相关

  • 定义特殊方法的装饰器

    • classmethod

      定义类方法

       class A:
           @classmethod
           def print(self):
               print('from A')
      
       A.print()  # from A
    • classmethod

      定义静态方法

       class A:
           @staticmethod
           def print():
               print('from A')
      
       A.print()  # from A
    • property

      将方法包装成属性

       class Person:
           def __init__(self, name, age):
               self.__name = name
               self.__age = age
      
           @property
           def name(self):
               return self.__name
      
           @name.setter
           def name(self, new_name):
               self.__name = new_name
      
           @name.deleter
           def name(self):
               print('执行删除name操作')
      
       p = Person('张三', 18)
       print(p.name)  # 张三
       p.name = '李四'
       print(p.name)  # 李四
       # 只是触发对应deleter装饰的函数,具体操作需在函数类完成
       del p.name  # 执行删除name操作
       print(p.name)  # 李四
  • 判断对象/类与类之间的关系

    • isinstance()

      判断一个对象是不是指定类的实例

       class A: pass
      
       class B: pass
      
       a = A()
       print(isinstance(a, A))  # True
      
       print(isinstance(a, B))  # False
    • issubclass()

      判断一个类指定类的子类

       class A: pass
      
       class B(A): pass
      
       class C: pass
      
       print(issubclass(B, A))  # True
       print(issubclass(B, C))  # False
    • object()

      所有类的基类

       class A: pass
      
       class B(A): pass
      
       class C: pass
      
       print(issubclass(A, object))  # True
       print(issubclass(B, object))  # True
       print(issubclass(C, object))  # True
    • super()

      获取父类

       class A:
           @classmethod
           def func(self):
               print('print in A')
      
       class B(A):
           @classmethod
           def func(self):
               super().func()
               super(B, self).func()
               print('print in B')
      
       B.func()
      
       # result:
       # print in A
       # print in A
       # print in B

其它

  • 作用域相关

    • locals()

      将当前函数块的所有变量以字典类型返回

       a = 1
       def outer():
           a = 2
           def inner():
               b = 3
               print(locals())
           inner()
      
       outer()
       # result
       # {'b': 3}
    • globals()

      将全局变量以字典类型返回

       a = 1
       def outer():
           a = 2
           def inner():
               b = 3
               print(globals())
           inner()
      
       outer()
       # result
       # {'__name__': '__main__', '__doc__': None, '__package__': None, ..., 'a': 1, 'outer': <function outer at 0x000000000203C268>}
  • 迭代器/生成器相关

    • range()

      返回指定区间数字生成器

       for i in range(1, 4):
           print(i)
       # result:
      
    • iter()

      传入可迭代对象返回迭代器

       print(iter(range(1, 4)))  # <range_iterator object at 0x0000000002792470>
    • next()

      迭代器取下一个值

       range_iter = iter(range(1, 3))
      
       print(range_iter.__next__())  # StopIteration 取不到值抛异常
  • 字符串类型代码的执行

    • eval()

      执行且有返回值

       
    • exec()

      执行无返回值

       print(exec('1+1'))  # None
    • compile()

      返回字符串编译后字节代码对象

       str = "for i in range(0,10): print(i)"
       c = compile(str, '', 'exec')  # 编译为字节代码对象
       exec(c)
       # result:
      
       str = "3 * 4 + 5"
       a = compile(str, '', 'eval')
       
  • 反射相关

    • hasattr()

      判断指定类或实例是否拥有指定属性

       class Person:
           gender = '男'
      
           def __init__(self, name, age):
               self.name = name
               self.age = age
      
       # 判断Person的实例p是否拥有name属性
       p = Person('张三', '李四')
       print(hasattr(p, 'name'))  # True
       # 判断Person类是否拥有name属性
       print(hasattr(Person, 'name'))  # False
       # 判断Person类是否拥有gender属性
       print(hasattr(Person, 'gender'))  # True
    • getattr()

      获取指定类或实例的指定属性引用

       class Person:
           gender = '男'
      
           def __init__(self, name, age):
               self.name = name
               self.age = age
      
           def show_name(self):
               print(self.name)
      
       p = Person('张三', 18)
       # 获取实例的属性
       print(getattr(p, 'age'))
       # 获取实例的方法
       getattr(p, 'show_name')()
    • setattr()

      给指定类或对象的属性赋值,没有则创建后再赋值

       class Person:
           def __init__(self, name, age):
               self.name = name
               self.age = age
      
           def show_name(self):
               print(self.name)
      
       print(hasattr(Person, 'gender'))  # False  默认没有gender属性
       setattr(Person, 'gender', '男')
       print(hasattr(Person, 'gender'))  # True
    • delattr()

      删除指定类或对象的指定属性

       class Person:
           gender = '男'
      
           def __init__(self, name, age):
               self.name = name
               self.age = age
      
           def show_name(self):
               print(self.name)
      
       print(hasattr(Person, 'gender'))  # True
       delattr(Person, 'gender')
       print(hasattr(Person, 'gender'))  # False
  • 输入输出

    • input()

      以字符串类型返回输入值

       >>> input('input your name:')
       input your name:zhangsan
       'zhangsan'
    • print()

      输出

       >>> print('hello world')
       hello world
  • 内存相关

    • hash()

      返回对象在内存中的哈希标识

       print(hash('a'))  # -1985915095439783199
    • id()

      返回对象在内存中的地址标识

       
  • 文件操作相关

  • 模块相关

    • __import__()

      模块导入

       time =__import__('time')# 等价于 import time
       print(time.time())
  • 调用相关

    • callable()

      判断对象是否可调用,返回True或False

       def func():
           return 1 + 1
      
       a = 1
       print(callable(a))  # False
       a = func
       print(callable(a))  # True
  • 查看信息

    • help()

      返回类型的帮助信息

       print(help(str))
       # result:
       # 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).
       #  |  encoding defaults to sys.getdefaultencoding().
       #  |  errors defaults to 'strict'.
       #  |
       #  |  Methods defined here:
       #  |
       #  |  __add__(self, value, /)
       #  |      Return self+value.
       #  |
       #  |  __contains__(self, key, /)
       #  |      Return key in self.
       #  |
       #  |  __eq__(self, value, /)
       #  |      Return self==value.
       #  |
       #  |  __format__(self, format_spec, /)
       #  |      Return a formatted version of the string as described by format_spec.
       #  |
       #  |  __ge__(self, value, /)
       #  |      Return self>=value.
       #  |
       #  |  __getattribute__(self, name, /)
       #  |      Return getattr(self, name).
       #  |
       #  |  __getitem__(self, key, /)
       #  |      Return self[key].
       #  |
       #  |  __getnewargs__(...)
       #  |
       #  |  __gt__(self, value, /)
       #  |      Return self>value.
       #  |
       #  |  __hash__(self, /)
       #  |      Return hash(self).
       #  |
       #  |  __iter__(self, /)
       #  |      Implement iter(self).
       #  |
       #  |  __le__(self, value, /)
       #  |      Return self<=value.
       #  |
       #  |  __len__(self, /)
       #  |      Return len(self).
       #  |
       #  |  __lt__(self, value, /)
       #  |      Return self<value.
       #  |
       #  |  __mod__(self, value, /)
       #  |      Return self%value.
       #  |
       #  |  __mul__(self, value, /)
       #  |      Return self*value.
       #  |
       #  |  __ne__(self, value, /)
       #  |      Return self!=value.
       #  |
       #  |  __repr__(self, /)
       #  |      Return repr(self).
       #  |
       #  |  __rmod__(self, value, /)
       #  |      Return value%self.
       #  |
       #  |  __rmul__(self, value, /)
       #  |      Return value*self.
       #  |
       #  |  __sizeof__(self, /)
       #  |      Return the size of the string in memory, in bytes.
       #  |
       #  |  __str__(self, /)
       #  |      Return str(self).
       #  |
       #  |  capitalize(self, /)
       #  |      Return a capitalized version of the string.
       #  |
       #  |      More specifically, make the first character have upper case and the rest lower
       #  |      case.
       #  |
       #  |  casefold(self, /)
       #  |      Return a version of the string suitable for caseless comparisons.
       #  |
       #  |  center(self, width, fillchar=' ', /)
       #  |      Return a centered string of length width.
       #  |
       #  |      Padding is done using the specified fill character (default is a space).
       #  |
       #  |  count(...)
       #  |      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.
       #  |
       #  |  encode(self, /, encoding='utf-8', errors='strict')
       #  |      Encode the string using the codec registered for encoding.
       #  |
       #  |      encoding
       #  |        The encoding in which to encode the string.
       #  |      errors
       #  |        The error handling scheme to use for encoding errors.
       #  |        The 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.
       #  |
       #  |  endswith(...)
       #  |      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.
       #  |
       #  |  expandtabs(self, /, tabsize=8)
       #  |      Return a copy where all tab characters are expanded using spaces.
       #  |
       #  |      If tabsize is not given, a tab size of 8 characters is assumed.
       #  |
       #  |  find(...)
       #  |      S.find(sub[, start[, end]]) -> 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.
       #  |
       #  |      Return -1 on failure.
       #  |
       #  |  format(...)
       #  |      S.format(*args, **kwargs) -> str
       #  |
       #  |      Return a formatted version of S, using substitutions from args and kwargs.
       #  |      The substitutions are identified by braces ('{' and '}').
       #  |
       #  |  format_map(...)
       #  |      S.format_map(mapping) -> str
       #  |
       #  |      Return a formatted version of S, using substitutions from mapping.
       #  |      The substitutions are identified by braces ('{' and '}').
       #  |
       #  |  index(...)
       #  |      S.index(sub[, start[, end]]) -> 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.
       #  |
       #  |      Raises ValueError when the substring is not found.
       #  |
       #  |  isalnum(self, /)
       #  |      Return True if the string is an alpha-numeric string, False otherwise.
       #  |
       #  |      A string is alpha-numeric if all characters in the string are alpha-numeric and
       #  |      there is at least one character in the string.
       #  |
       #  |  isalpha(self, /)
       #  |      Return True if the string is an alphabetic string, False otherwise.
       #  |
       #  |      A string is alphabetic if all characters in the string are alphabetic and there
       #  |      is at least one character in the string.
       #  |
       #  |  isascii(self, /)
       #  |      Return True if all characters in the string are ASCII, False otherwise.
       #  |
       #  |      ASCII characters have code points in the range U+0000-U+007F.
       #  |      Empty string is ASCII too.
       #  |
       #  |  isdecimal(self, /)
       #  |      Return True if the string is a decimal string, False otherwise.
       #  |
       #  |      A string is a decimal string if all characters in the string are decimal and
       #  |      there is at least one character in the string.
       #  |
       #  |  isdigit(self, /)
       #  |      Return True if the string is a digit string, False otherwise.
       #  |
       #  |      A string is a digit string if all characters in the string are digits and there
       #  |      is at least one character in the string.
       #  |
       #  |  isidentifier(self, /)
       #  |      Return True if the string is a valid Python identifier, False otherwise.
       #  |
       #  |      Use keyword.iskeyword() to test for reserved identifiers such as "def" and
       #  |      "class".
       #  |
       #  |  islower(self, /)
       #  |      Return True if the string is a lowercase string, False otherwise.
       #  |
       #  |      A string is lowercase if all cased characters in the string are lowercase and
       #  |      there is at least one cased character in the string.
       #  |
       #  |  isnumeric(self, /)
       #  |      Return True if the string is a numeric string, False otherwise.
       #  |
       #  |      A string is numeric if all characters in the string are numeric and there is at
       #  |      least one character in the string.
       #  |
       #  |  isprintable(self, /)
       #  |      Return True if the string is printable, False otherwise.
       #  |
       #  |      A string is printable if all of its characters are considered printable in
       #  |      repr() or if it is empty.
       #  |
       #  |  isspace(self, /)
       #  |      Return True if the string is a whitespace string, False otherwise.
       #  |
       #  |      A string is whitespace if all characters in the string are whitespace and there
       #  |      is at least one character in the string.
       #  |
       #  |  istitle(self, /)
       #  |      Return True if the string is a title-cased string, False otherwise.
       #  |
       #  |      In a title-cased string, upper- and title-case characters may only
       #  |      follow uncased characters and lowercase characters only cased ones.
       #  |
       #  |  isupper(self, /)
       #  |      Return True if the string is an uppercase string, False otherwise.
       #  |
       #  |      A string is uppercase if all cased characters in the string are uppercase and
       #  |      there is at least one cased character in the string.
       #  |
       #  |  join(self, iterable, /)
       #  |      Concatenate any number of strings.
       #  |
       #  |      The string whose method is called is inserted in between each given string.
       #  |      The result is returned as a new string.
       #  |
       #  |      Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
       #  |
       #  |  ljust(self, width, fillchar=' ', /)
       #  |      Return a left-justified string of length width.
       #  |
       #  |      Padding is done using the specified fill character (default is a space).
       #  |
       #  |  lower(self, /)
       #  |      Return a copy of the string converted to lowercase.
       #  |
       #  |  lstrip(self, chars=None, /)
       #  |      Return a copy of the string with leading whitespace removed.
       #  |
       #  |      If chars is given and not None, remove characters in chars instead.
       #  |
       #  |  partition(self, sep, /)
       #  |      Partition the string into three parts using the given separator.
       #  |
       #  |      This will search for the separator in the string.  If the separator is found,
       #  |      returns a 3-tuple containing the part before the separator, the separator
       #  |      itself, and the part after it.
       #  |
       #  |      If the separator is not found, returns a 3-tuple containing the original string
       #  |      and two empty strings.
       #  |
       #  |  replace(self, old, new, count=-1, /)
       #  |      Return a copy with all occurrences of substring old replaced by new.
       #  |
       #  |        count
       #  |          Maximum number of occurrences to replace.
       #  |          -1 (the default value) means replace all occurrences.
       #  |
       #  |      If the optional argument count is given, only the first count occurrences are
       #  |      replaced.
       #  |
       #  |  rfind(...)
       #  |      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.
       #  |
       #  |  rindex(...)
       #  |      S.rindex(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.
       #  |
       #  |      Raises ValueError when the substring is not found.
       #  |
       #  |  rjust(self, width, fillchar=' ', /)
       #  |      Return a right-justified string of length width.
       #  |
       #  |      Padding is done using the specified fill character (default is a space).
       #  |
       #  |  rpartition(self, sep, /)
       #  |      Partition the string into three parts using the given separator.
       #  |
       #  |      This will search for the separator in the string, starting at the end. If
       #  |      the separator is found, returns a 3-tuple containing the part before the
       #  |      separator, the separator itself, and the part after it.
       #  |
       #  |      If the separator is not found, returns a 3-tuple containing two empty strings
       #  |      and the original string.
       #  |
       #  |  rsplit(self, /, sep=None, maxsplit=-1)
       #  |      Return a list of the words in the string, using sep as the delimiter string.
       #  |
       #  |        sep
       #  |          The delimiter according which to split the string.
       #  |          None (the default value) means split according to any whitespace,
       #  |          and discard empty strings from the result.
       #  |        maxsplit
       #  |          Maximum number of splits to do.
       #  |          -1 (the default value) means no limit.
       #  |
       #  |      Splits are done starting at the end of the string and working to the front.
       #  |
       #  |  rstrip(self, chars=None, /)
       #  |      Return a copy of the string with trailing whitespace removed.
       #  |
       #  |      If chars is given and not None, remove characters in chars instead.
       #  |
       #  |  split(self, /, sep=None, maxsplit=-1)
       #  |      Return a list of the words in the string, using sep as the delimiter string.
       #  |
       #  |      sep
       #  |        The delimiter according which to split the string.
       #  |        None (the default value) means split according to any whitespace,
       #  |        and discard empty strings from the result.
       #  |      maxsplit
       #  |        Maximum number of splits to do.
       #  |        -1 (the default value) means no limit.
       #  |
       #  |  splitlines(self, /, keepends=False)
       #  |      Return a list of the lines in the string, breaking at line boundaries.
       #  |
       #  |      Line breaks are not included in the resulting list unless keepends is given and
       #  |      true.
       #  |
       #  |  startswith(...)
       #  |      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.
       #  |
       #  |  strip(self, chars=None, /)
       #  |      Return a copy of the string with leading and trailing whitespace remove.
       #  |
       #  |      If chars is given and not None, remove characters in chars instead.
       #  |
       #  |  swapcase(self, /)
       #  |      Convert uppercase characters to lowercase and lowercase characters to uppercase.
       #  |
       #  |  title(self, /)
       #  |      Return a version of the string where each word is titlecased.
       #  |
       #  |      More specifically, words start with uppercased characters and all remaining
       #  |      cased characters have lower case.
       #  |
       #  |  translate(self, table, /)
       #  |      Replace each character in the string using the given translation table.
       #  |
       #  |        table
       #  |          Translation table, which must be a mapping of Unicode ordinals to
       #  |          Unicode ordinals, strings, or None.
       #  |
       #  |      The table must implement lookup/indexing via __getitem__, for instance a
       #  |      dictionary or list.  If this operation raises LookupError, the character is
       #  |      left untouched.  Characters mapped to None are deleted.
       #  |
       #  |  upper(self, /)
       #  |      Return a copy of the string converted to uppercase.
       #  |
       #  |  zfill(self, width, /)
       #  |      Pad a numeric string with zeros on the left, to fill a field of the given width.
       #  |
       #  |      The string is never truncated.
       #  |
       #  |  ----------------------------------------------------------------------
       #  |  Static methods defined here:
       #  |
       #  |  __new__(*args, **kwargs) from builtins.type
       #  |      Create and return a new object.  See help(type) for accurate signature.
       #  |
       #  |  maketrans(x, y=None, z=None, /)
       #  |      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.
       #
       # None
       #
    • dir()

      以字符串列表返回对象类型的属性及函数

       print(dir(
           'a'))  # ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']