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

匿名函数

例子

  • 返回两个数的和
    1 def add(x, y):
    2     return x + y
    3 
    4 # 等价于
    5 
    6 add = lambda x, y: x + y
    7 print(add(1, 2))  # 3
    View Code
  • 返回字典中值最大的key
    1 dic = {'a': 13, 'b': 3, 'c': 34}
    2 print(max(dic,key=lambda x:dic[x]))
    View Code

面试题

  • 题1

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

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

    写出下列代码输出结果

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

内置函数

数字相关

  • 数据类型转换
    • bool()

      转布尔类型

      1 print(bool([]))  # False
      2 print(bool(''))  # False
      3 print(bool(0))  # False
      4 print(bool({}))  # False
      5 print(bool(()))  # False
      View Code
    • int()

      转整形

      1 print(int('3'))  # 3
      View Code
    • float()

      转浮点型

      1 print(float('3'))  # 3.0
      View Code
    • complex()

      转复数类型

      1 print(complex('3'))  # (3+0j)
      View Code
  • 进制转换
    • bin()

      转二进制

      1 print(bin(2))  # 0b10
      View Code
    • oct()

      转八进制

      1 print(oct(2))  # 0o2
      View Code
    • hex()

      转十六进制

      1 print(hex(2))  # 0x2
      View Code
  • 数学运算
    • abs()

      绝对值

      1 print(abs(-3))  # 3
      View Code
    • divmod()

      除余

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

      精确小数位

      1 print(round(3.5687789,3))  # 3.569
      View Code
    • pow()

      幂运算

      1 print(pow(2,3))  # 8
      View Code
    • sum()

      求和

      1 print(sum([2,3]))  # 5
      View Code
    • max()

      最大值

      1 print(max([2,3]))  # 3
      View Code
    • min()

      最小值

      1 print(min([2,3]))  # 2
      View Code

数据结构相关

  • 类型转换
    • list()

      转列表类型

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

      转元组类型

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

      转字典类型

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

      转集合类型

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

      转不可变集合类型

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

      转字符串

      1 print(str(123))  # 123
      View Code
    • format()

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

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

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

       1 print(format(3.1415926))  # 3.1415926
       2 # 字符串:指定对齐方式,<是左对齐, >是右对齐,^是居中对齐
       3 print(format('format', '<20'))
       4 print(format('format', '>20'))
       5 print(format('format', '^20'))
       6 # result:
       7 # format
       8 #               format
       9 #        format
      10 
      11 # 整形:
      12 # 转换成二进制
      13 print(format(3, 'b'))  # 11
      14 # 转换unicode成字符
      15 print(format(97, 'c'))  # a
      16 # 转换成10进制
      17 print(format(11, 'd'))  # 11
      18 # 转换成8进制
      19 print(format(11, 'o'))  # 13
      20 # 转换成16进制 小写字母表示
      21 print(format(11, 'x'))  # b
      22 # 转换成16进制 大写字母表示
      23 print(format(11, 'X'))  # B
      24 # 和d一样
      25 print(format(11, 'n'))  # 11
      26 # 默认和d一样
      27 print(format(11))  # 11
      28 
      29 # 浮点型:
      30 # 科学计数法,默认保留6位小数
      31 print(format(314159267, 'e'))  # '3.141593e+08'
      32 # 科学计数法,指定保留2位小数
      33 print(format(314159267, '0.2e'))  # '3.14e+08'
      34 # 科学计数法,指定保留2位小数,采用大写E表示
      35 print(format(314159267, '0.2E'))  # '3.14E+08'
      36 # 小数点计数法,默认保留6位小数
      37 print(format(314159267, 'f'))  # '314159267.000000'
      38 # 小数点计数法,默认保留6位小数
      39 print(format(3.14159267000, 'f'))  # '3.141593'
      40 ##小数点计数法,指定保留8位小数
      41 print(format(3.14159267000, '0.8f'))  # '3.14159267'
      42 # 小数点计数法,指定保留10位小数
      43 print(format(3.14159267000, '0.10f'))  # '3.1415926700'
      44 # 小数点计数法,无穷大转换成大小字母
      45 print(format(3.14e+1000000, 'F'))  # 'INF'
      View Code
    • bytes()

      转字节

      1 print(bytes('aaa', 'utf8'))  # b'aaa'
      2 print('aaa'.encode('utf8'))  # b'aaa'
      View Code
    • bytearray()

      转字节数组

      1 print(bytearray('aaa', 'utf8'))  # bytearray(b'aaa')
      2 for i in bytearray('aaa', 'utf8'):
      3     print(i)
      4     # 97
      5     # 97
      6     # 97
      View Code
    • memoryview()

      查看bytes内存地址

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

      字符按unicode转数字

      1 print(ord('a'))  # 97
      View Code
    • chr()

      数字按unicode转字符

      1 print(chr(97))  # 'a'
      View Code
    • ascii()

      转ascii码

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

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

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

      返回可迭代对象长度

      1 print(len([1, 1, 1]))  # 3
      2 print(len('111'))  # 3
      3 print(len({1: 'a', 2: 'b', 3: 'c'}))  # 3
      View Code
    • enumerate()

      枚举化

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

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

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

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

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

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

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

      过滤

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

      映射

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

      排序

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

面向对象相关

  • 定义特殊方法的装饰器
    • classmethod

      定义类方法

      1 class A:
      2     @classmethod
      3     def print(self):
      4         print('from A')
      5 
      6 
      7 A.print()  # from A
      View Code
    • classmethod

      定义静态方法

      1 class A:
      2     @staticmethod
      3     def print():
      4         print('from A')
      5 
      6 
      7 A.print()  # from A
      View Code
    • property

      将方法包装成属性

       1 class Person:
       2     def __init__(self, name, age):
       3         self.__name = name
       4         self.__age = age
       5 
       6     @property
       7     def name(self):
       8         return self.__name
       9 
      10     @name.setter
      11     def name(self, new_name):
      12         self.__name = new_name
      13 
      14     @name.deleter
      15     def name(self):
      16         print('执行删除name操作')
      17 
      18 
      19 p = Person('张三', 18)
      20 print(p.name)  # 张三
      21 p.name = '李四'
      22 print(p.name)  # 李四
      23 # 只是触发对应deleter装饰的函数,具体操作需在函数类完成
      24 del p.name  # 执行删除name操作
      25 print(p.name)  # 李四
      View Code
  • 判断对象/类与类之间的关系
    • isinstance()

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

      1 class A: pass
      2 
      3 class B: pass
      4 
      5 a = A()
      6 print(isinstance(a, A))  # True
      7 
      8 print(isinstance(a, B))  # False
      View Code
    • issubclass()

      判断一个类指定类的子类

      1 class A: pass
      2 
      3 class B(A): pass
      4 
      5 class C: pass
      6 
      7 print(issubclass(B, A))  # True
      8 print(issubclass(B, C))  # False
      View Code
    • object()

      所有类的基类

      1 class A: pass
      2 
      3 class B(A): pass
      4 
      5 class C: pass
      6 
      7 print(issubclass(A, object))  # True
      8 print(issubclass(B, object))  # True
      9 print(issubclass(C, object))  # True
      View Code
    • super()

      获取父类

       1 class A:
       2     @classmethod
       3     def func(self):
       4         print('print in A')
       5 
       6 class B(A):
       7     @classmethod
       8     def func(self):
       9         super().func()
      10         super(B, self).func()
      11         print('print in B')
      12 
      13 B.func()
      14 
      15 # result:
      16 # print in A
      17 # print in A
      18 # print in B
      View Code

其它

  • 作用域相关
    • locals()

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

       1 a = 1
       2 def outer():
       3     a = 2
       4     def inner():
       5         b = 3
       6         print(locals())
       7     inner()
       8     
       9 outer()
      10 # result
      11 # {'b': 3}
      View Code
    • globals()

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

       1 a = 1
       2 def outer():
       3     a = 2
       4     def inner():
       5         b = 3
       6         print(globals())
       7     inner()
       8 
       9 outer()
      10 # result
      11 # {'__name__': '__main__', '__doc__': None, '__package__': None, ..., 'a': 1, 'outer': <function outer at 0x000000000203C268>}
      View Code
  • 迭代器/生成器相关
    • range()

      返回指定区间数字生成器

      1 for i in range(1, 4):
      2     print(i)
      3 # result:
      4 # 1
      5 # 2
      6 # 3
      View Code
    • iter()

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

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

      迭代器取下一个值

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

      执行且有返回值

      1 print(eval('1+1'))  # 2
      View Code
    • exec()

      执行无返回值

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

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

       1 str = "for i in range(0,10): print(i)"
       2 c = compile(str, '', 'exec')  # 编译为字节代码对象
       3 exec(c)
       4 # result:
       5 # 1
       6 # 2
       7 # 3
       8 # 4
       9 # 5
      10 # 6
      11 # 7
      12 # 8
      13 # 9
      14 str = "3 * 4 + 5"
      15 a = compile(str, '', 'eval')
      16 print(eval(a))  # 17
      View Code
  • 反射相关
    • hasattr()

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

       1 class Person:
       2     gender = ''
       3 
       4     def __init__(self, name, age):
       5         self.name = name
       6         self.age = age
       7 
       8 
       9 # 判断Person的实例p是否拥有name属性
      10 p = Person('张三', '李四')
      11 print(hasattr(p, 'name'))  # True
      12 # 判断Person类是否拥有name属性
      13 print(hasattr(Person, 'name'))  # False
      14 # 判断Person类是否拥有gender属性
      15 print(hasattr(Person, 'gender'))  # True
      View Code
    • getattr()

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

       1 class Person:
       2     gender = ''
       3 
       4     def __init__(self, name, age):
       5         self.name = name
       6         self.age = age
       7 
       8     def show_name(self):
       9         print(self.name)
      10 
      11 
      12 p = Person('张三', 18)
      13 # 获取实例的属性
      14 print(getattr(p, 'age'))
      15 # 获取实例的方法
      16 getattr(p, 'show_name')()
      View Code
    • setattr()

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

       1 class Person:
       2     def __init__(self, name, age):
       3         self.name = name
       4         self.age = age
       5 
       6     def show_name(self):
       7         print(self.name)
       8 
       9 
      10 print(hasattr(Person, 'gender'))  # False  默认没有gender属性
      11 setattr(Person, 'gender', '')
      12 print(hasattr(Person, 'gender'))  # True
      View Code
    • delattr()

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

       1 class Person:
       2     gender = ''
       3 
       4     def __init__(self, name, age):
       5         self.name = name
       6         self.age = age
       7 
       8     def show_name(self):
       9         print(self.name)
      10 
      11 
      12 print(hasattr(Person, 'gender'))  # True
      13 delattr(Person, 'gender')
      14 print(hasattr(Person, 'gender'))  # False
      View Code
  • 输入输出
    • input()

      以字符串类型返回输入值

      1 >>> input('input your name:')
      2 input your name:zhangsan
      3 'zhangsan'
      View Code
    • print()

      输出

      1 >>> print('hello world')
      2 hello world
      View Code
  • 内存相关
    • hash()

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

      1 print(hash('a'))  # -1985915095439783199
      View Code
    • id()

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

      1 print(id('a'))  # 34187784
      View Code
  • 文件操作相关
  • 模块相关
    • __import__()

      模块导入

      1 time =__import__('time')# 等价于 import time
      2 print(time.time())
      View Code
  • 调用相关
    • callable()

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

      1 def func():
      2     return 1 + 1
      3 
      4 a = 1
      5 print(callable(a))  # False
      6 a = func
      7 print(callable(a))  # True
      View Code  
  • 查看信息
    • help()

      返回类型的帮助信息

        1 print(help(str))
        2 # result:
        3 # class str(object)
        4 #  |  str(object='') -> str
        5 #  |  str(bytes_or_buffer[, encoding[, errors]]) -> str
        6 #  |
        7 #  |  Create a new string object from the given object. If encoding or
        8 #  |  errors is specified, then the object must expose a data buffer
        9 #  |  that will be decoded using the given encoding and error handler.
       10 #  |  Otherwise, returns the result of object.__str__() (if defined)
       11 #  |  or repr(object).
       12 #  |  encoding defaults to sys.getdefaultencoding().
       13 #  |  errors defaults to 'strict'.
       14 #  |
       15 #  |  Methods defined here:
       16 #  |
       17 #  |  __add__(self, value, /)
       18 #  |      Return self+value.
       19 #  |
       20 #  |  __contains__(self, key, /)
       21 #  |      Return key in self.
       22 #  |
       23 #  |  __eq__(self, value, /)
       24 #  |      Return self==value.
       25 #  |
       26 #  |  __format__(self, format_spec, /)
       27 #  |      Return a formatted version of the string as described by format_spec.
       28 #  |
       29 #  |  __ge__(self, value, /)
       30 #  |      Return self>=value.
       31 #  |
       32 #  |  __getattribute__(self, name, /)
       33 #  |      Return getattr(self, name).
       34 #  |
       35 #  |  __getitem__(self, key, /)
       36 #  |      Return self[key].
       37 #  |
       38 #  |  __getnewargs__(...)
       39 #  |
       40 #  |  __gt__(self, value, /)
       41 #  |      Return self>value.
       42 #  |
       43 #  |  __hash__(self, /)
       44 #  |      Return hash(self).
       45 #  |
       46 #  |  __iter__(self, /)
       47 #  |      Implement iter(self).
       48 #  |
       49 #  |  __le__(self, value, /)
       50 #  |      Return self<=value.
       51 #  |
       52 #  |  __len__(self, /)
       53 #  |      Return len(self).
       54 #  |
       55 #  |  __lt__(self, value, /)
       56 #  |      Return self<value.
       57 #  |
       58 #  |  __mod__(self, value, /)
       59 #  |      Return self%value.
       60 #  |
       61 #  |  __mul__(self, value, /)
       62 #  |      Return self*value.
       63 #  |
       64 #  |  __ne__(self, value, /)
       65 #  |      Return self!=value.
       66 #  |
       67 #  |  __repr__(self, /)
       68 #  |      Return repr(self).
       69 #  |
       70 #  |  __rmod__(self, value, /)
       71 #  |      Return value%self.
       72 #  |
       73 #  |  __rmul__(self, value, /)
       74 #  |      Return value*self.
       75 #  |
       76 #  |  __sizeof__(self, /)
       77 #  |      Return the size of the string in memory, in bytes.
       78 #  |
       79 #  |  __str__(self, /)
       80 #  |      Return str(self).
       81 #  |
       82 #  |  capitalize(self, /)
       83 #  |      Return a capitalized version of the string.
       84 #  |
       85 #  |      More specifically, make the first character have upper case and the rest lower
       86 #  |      case.
       87 #  |
       88 #  |  casefold(self, /)
       89 #  |      Return a version of the string suitable for caseless comparisons.
       90 #  |
       91 #  |  center(self, width, fillchar=' ', /)
       92 #  |      Return a centered string of length width.
       93 #  |
       94 #  |      Padding is done using the specified fill character (default is a space).
       95 #  |
       96 #  |  count(...)
       97 #  |      S.count(sub[, start[, end]]) -> int
       98 #  |
       99 #  |      Return the number of non-overlapping occurrences of substring sub in
      100 #  |      string S[start:end].  Optional arguments start and end are
      101 #  |      interpreted as in slice notation.
      102 #  |
      103 #  |  encode(self, /, encoding='utf-8', errors='strict')
      104 #  |      Encode the string using the codec registered for encoding.
      105 #  |
      106 #  |      encoding
      107 #  |        The encoding in which to encode the string.
      108 #  |      errors
      109 #  |        The error handling scheme to use for encoding errors.
      110 #  |        The default is 'strict' meaning that encoding errors raise a
      111 #  |        UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and
      112 #  |        'xmlcharrefreplace' as well as any other name registered with
      113 #  |        codecs.register_error that can handle UnicodeEncodeErrors.
      114 #  |
      115 #  |  endswith(...)
      116 #  |      S.endswith(suffix[, start[, end]]) -> bool
      117 #  |
      118 #  |      Return True if S ends with the specified suffix, False otherwise.
      119 #  |      With optional start, test S beginning at that position.
      120 #  |      With optional end, stop comparing S at that position.
      121 #  |      suffix can also be a tuple of strings to try.
      122 #  |
      123 #  |  expandtabs(self, /, tabsize=8)
      124 #  |      Return a copy where all tab characters are expanded using spaces.
      125 #  |
      126 #  |      If tabsize is not given, a tab size of 8 characters is assumed.
      127 #  |
      128 #  |  find(...)
      129 #  |      S.find(sub[, start[, end]]) -> int
      130 #  |
      131 #  |      Return the lowest index in S where substring sub is found,
      132 #  |      such that sub is contained within S[start:end].  Optional
      133 #  |      arguments start and end are interpreted as in slice notation.
      134 #  |
      135 #  |      Return -1 on failure.
      136 #  |
      137 #  |  format(...)
      138 #  |      S.format(*args, **kwargs) -> str
      139 #  |
      140 #  |      Return a formatted version of S, using substitutions from args and kwargs.
      141 #  |      The substitutions are identified by braces ('{' and '}').
      142 #  |
      143 #  |  format_map(...)
      144 #  |      S.format_map(mapping) -> str
      145 #  |
      146 #  |      Return a formatted version of S, using substitutions from mapping.
      147 #  |      The substitutions are identified by braces ('{' and '}').
      148 #  |
      149 #  |  index(...)
      150 #  |      S.index(sub[, start[, end]]) -> int
      151 #  |
      152 #  |      Return the lowest index in S where substring sub is found,
      153 #  |      such that sub is contained within S[start:end].  Optional
      154 #  |      arguments start and end are interpreted as in slice notation.
      155 #  |
      156 #  |      Raises ValueError when the substring is not found.
      157 #  |
      158 #  |  isalnum(self, /)
      159 #  |      Return True if the string is an alpha-numeric string, False otherwise.
      160 #  |
      161 #  |      A string is alpha-numeric if all characters in the string are alpha-numeric and
      162 #  |      there is at least one character in the string.
      163 #  |
      164 #  |  isalpha(self, /)
      165 #  |      Return True if the string is an alphabetic string, False otherwise.
      166 #  |
      167 #  |      A string is alphabetic if all characters in the string are alphabetic and there
      168 #  |      is at least one character in the string.
      169 #  |
      170 #  |  isascii(self, /)
      171 #  |      Return True if all characters in the string are ASCII, False otherwise.
      172 #  |
      173 #  |      ASCII characters have code points in the range U+0000-U+007F.
      174 #  |      Empty string is ASCII too.
      175 #  |
      176 #  |  isdecimal(self, /)
      177 #  |      Return True if the string is a decimal string, False otherwise.
      178 #  |
      179 #  |      A string is a decimal string if all characters in the string are decimal and
      180 #  |      there is at least one character in the string.
      181 #  |
      182 #  |  isdigit(self, /)
      183 #  |      Return True if the string is a digit string, False otherwise.
      184 #  |
      185 #  |      A string is a digit string if all characters in the string are digits and there
      186 #  |      is at least one character in the string.
      187 #  |
      188 #  |  isidentifier(self, /)
      189 #  |      Return True if the string is a valid Python identifier, False otherwise.
      190 #  |
      191 #  |      Use keyword.iskeyword() to test for reserved identifiers such as "def" and
      192 #  |      "class".
      193 #  |
      194 #  |  islower(self, /)
      195 #  |      Return True if the string is a lowercase string, False otherwise.
      196 #  |
      197 #  |      A string is lowercase if all cased characters in the string are lowercase and
      198 #  |      there is at least one cased character in the string.
      199 #  |
      200 #  |  isnumeric(self, /)
      201 #  |      Return True if the string is a numeric string, False otherwise.
      202 #  |
      203 #  |      A string is numeric if all characters in the string are numeric and there is at
      204 #  |      least one character in the string.
      205 #  |
      206 #  |  isprintable(self, /)
      207 #  |      Return True if the string is printable, False otherwise.
      208 #  |
      209 #  |      A string is printable if all of its characters are considered printable in
      210 #  |      repr() or if it is empty.
      211 #  |
      212 #  |  isspace(self, /)
      213 #  |      Return True if the string is a whitespace string, False otherwise.
      214 #  |
      215 #  |      A string is whitespace if all characters in the string are whitespace and there
      216 #  |      is at least one character in the string.
      217 #  |
      218 #  |  istitle(self, /)
      219 #  |      Return True if the string is a title-cased string, False otherwise.
      220 #  |
      221 #  |      In a title-cased string, upper- and title-case characters may only
      222 #  |      follow uncased characters and lowercase characters only cased ones.
      223 #  |
      224 #  |  isupper(self, /)
      225 #  |      Return True if the string is an uppercase string, False otherwise.
      226 #  |
      227 #  |      A string is uppercase if all cased characters in the string are uppercase and
      228 #  |      there is at least one cased character in the string.
      229 #  |
      230 #  |  join(self, iterable, /)
      231 #  |      Concatenate any number of strings.
      232 #  |
      233 #  |      The string whose method is called is inserted in between each given string.
      234 #  |      The result is returned as a new string.
      235 #  |
      236 #  |      Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
      237 #  |
      238 #  |  ljust(self, width, fillchar=' ', /)
      239 #  |      Return a left-justified string of length width.
      240 #  |
      241 #  |      Padding is done using the specified fill character (default is a space).
      242 #  |
      243 #  |  lower(self, /)
      244 #  |      Return a copy of the string converted to lowercase.
      245 #  |
      246 #  |  lstrip(self, chars=None, /)
      247 #  |      Return a copy of the string with leading whitespace removed.
      248 #  |
      249 #  |      If chars is given and not None, remove characters in chars instead.
      250 #  |
      251 #  |  partition(self, sep, /)
      252 #  |      Partition the string into three parts using the given separator.
      253 #  |
      254 #  |      This will search for the separator in the string.  If the separator is found,
      255 #  |      returns a 3-tuple containing the part before the separator, the separator
      256 #  |      itself, and the part after it.
      257 #  |
      258 #  |      If the separator is not found, returns a 3-tuple containing the original string
      259 #  |      and two empty strings.
      260 #  |
      261 #  |  replace(self, old, new, count=-1, /)
      262 #  |      Return a copy with all occurrences of substring old replaced by new.
      263 #  |
      264 #  |        count
      265 #  |          Maximum number of occurrences to replace.
      266 #  |          -1 (the default value) means replace all occurrences.
      267 #  |
      268 #  |      If the optional argument count is given, only the first count occurrences are
      269 #  |      replaced.
      270 #  |
      271 #  |  rfind(...)
      272 #  |      S.rfind(sub[, start[, end]]) -> int
      273 #  |
      274 #  |      Return the highest index in S where substring sub is found,
      275 #  |      such that sub is contained within S[start:end].  Optional
      276 #  |      arguments start and end are interpreted as in slice notation.
      277 #  |
      278 #  |      Return -1 on failure.
      279 #  |
      280 #  |  rindex(...)
      281 #  |      S.rindex(sub[, start[, end]]) -> int
      282 #  |
      283 #  |      Return the highest index in S where substring sub is found,
      284 #  |      such that sub is contained within S[start:end].  Optional
      285 #  |      arguments start and end are interpreted as in slice notation.
      286 #  |
      287 #  |      Raises ValueError when the substring is not found.
      288 #  |
      289 #  |  rjust(self, width, fillchar=' ', /)
      290 #  |      Return a right-justified string of length width.
      291 #  |
      292 #  |      Padding is done using the specified fill character (default is a space).
      293 #  |
      294 #  |  rpartition(self, sep, /)
      295 #  |      Partition the string into three parts using the given separator.
      296 #  |
      297 #  |      This will search for the separator in the string, starting at the end. If
      298 #  |      the separator is found, returns a 3-tuple containing the part before the
      299 #  |      separator, the separator itself, and the part after it.
      300 #  |
      301 #  |      If the separator is not found, returns a 3-tuple containing two empty strings
      302 #  |      and the original string.
      303 #  |
      304 #  |  rsplit(self, /, sep=None, maxsplit=-1)
      305 #  |      Return a list of the words in the string, using sep as the delimiter string.
      306 #  |
      307 #  |        sep
      308 #  |          The delimiter according which to split the string.
      309 #  |          None (the default value) means split according to any whitespace,
      310 #  |          and discard empty strings from the result.
      311 #  |        maxsplit
      312 #  |          Maximum number of splits to do.
      313 #  |          -1 (the default value) means no limit.
      314 #  |
      315 #  |      Splits are done starting at the end of the string and working to the front.
      316 #  |
      317 #  |  rstrip(self, chars=None, /)
      318 #  |      Return a copy of the string with trailing whitespace removed.
      319 #  |
      320 #  |      If chars is given and not None, remove characters in chars instead.
      321 #  |
      322 #  |  split(self, /, sep=None, maxsplit=-1)
      323 #  |      Return a list of the words in the string, using sep as the delimiter string.
      324 #  |
      325 #  |      sep
      326 #  |        The delimiter according which to split the string.
      327 #  |        None (the default value) means split according to any whitespace,
      328 #  |        and discard empty strings from the result.
      329 #  |      maxsplit
      330 #  |        Maximum number of splits to do.
      331 #  |        -1 (the default value) means no limit.
      332 #  |
      333 #  |  splitlines(self, /, keepends=False)
      334 #  |      Return a list of the lines in the string, breaking at line boundaries.
      335 #  |
      336 #  |      Line breaks are not included in the resulting list unless keepends is given and
      337 #  |      true.
      338 #  |
      339 #  |  startswith(...)
      340 #  |      S.startswith(prefix[, start[, end]]) -> bool
      341 #  |
      342 #  |      Return True if S starts with the specified prefix, False otherwise.
      343 #  |      With optional start, test S beginning at that position.
      344 #  |      With optional end, stop comparing S at that position.
      345 #  |      prefix can also be a tuple of strings to try.
      346 #  |
      347 #  |  strip(self, chars=None, /)
      348 #  |      Return a copy of the string with leading and trailing whitespace remove.
      349 #  |
      350 #  |      If chars is given and not None, remove characters in chars instead.
      351 #  |
      352 #  |  swapcase(self, /)
      353 #  |      Convert uppercase characters to lowercase and lowercase characters to uppercase.
      354 #  |
      355 #  |  title(self, /)
      356 #  |      Return a version of the string where each word is titlecased.
      357 #  |
      358 #  |      More specifically, words start with uppercased characters and all remaining
      359 #  |      cased characters have lower case.
      360 #  |
      361 #  |  translate(self, table, /)
      362 #  |      Replace each character in the string using the given translation table.
      363 #  |
      364 #  |        table
      365 #  |          Translation table, which must be a mapping of Unicode ordinals to
      366 #  |          Unicode ordinals, strings, or None.
      367 #  |
      368 #  |      The table must implement lookup/indexing via __getitem__, for instance a
      369 #  |      dictionary or list.  If this operation raises LookupError, the character is
      370 #  |      left untouched.  Characters mapped to None are deleted.
      371 #  |
      372 #  |  upper(self, /)
      373 #  |      Return a copy of the string converted to uppercase.
      374 #  |
      375 #  |  zfill(self, width, /)
      376 #  |      Pad a numeric string with zeros on the left, to fill a field of the given width.
      377 #  |
      378 #  |      The string is never truncated.
      379 #  |
      380 #  |  ----------------------------------------------------------------------
      381 #  |  Static methods defined here:
      382 #  |
      383 #  |  __new__(*args, **kwargs) from builtins.type
      384 #  |      Create and return a new object.  See help(type) for accurate signature.
      385 #  |
      386 #  |  maketrans(x, y=None, z=None, /)
      387 #  |      Return a translation table usable for str.translate().
      388 #  |
      389 #  |      If there is only one argument, it must be a dictionary mapping Unicode
      390 #  |      ordinals (integers) or characters to Unicode ordinals, strings or None.
      391 #  |      Character keys will be then converted to ordinals.
      392 #  |      If there are two arguments, they must be strings of equal length, and
      393 #  |      in the resulting dictionary, each character in x will be mapped to the
      394 #  |      character at the same position in y. If there is a third argument, it
      395 #  |      must be a string, whose characters will be mapped to None in the result.
      396 #
      397 # None
      398 #
      View Code
    • dir()

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

      1 print(dir(
      2     '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']
      View Code  

转载于:https://www.cnblogs.com/zze46/p/9568589.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值