python 常用内置函数

1.字符串和bytes互转

  • 方法一:bytes(s) / str(b)
# s->b
>>> s='蓝天云'
>>> b=bytes(s,encoding="utf-8")
>>> b
b'\xe8\x93\x9d\xe5\xa4\xa9\xe4\xba\x91'
# b->s
>>> str(b,encoding="utf-8") #也可以写 str(b,encoding="utf8")
'蓝天云'
>>> str(b,"GBK") #会报错
  • 方法二:s.encode() / b.decode()
# s -> b
>>> s
'蓝天云'
>>> s.encode()
b'\xe8\x93\x9d\xe5\xa4\xa9\xe4\xba\x91'
>>> s.encode('GBK')
b'\xc0\xb6\xcc\xec\xd4\xc6'
# b->s
>>> s.encode('GBK').decode('GBK')
'蓝天云'
>>> s.encode().decode()
'蓝天云'
>>> s.encode('GBK').decode() #会报错. 加密方式为GBK,解密方式却是utf8

2.进制互转

  • 10转2,8,16 : bin(i),otc(i),hex(i)
>>> i = 10  # 十进制
>>> bin(i)  #二进制
'0b1010'  
>>> oct(i)  #八进制
'0o12'    
>>> hex(i) #十六进制
'0xa'
  • 2,8,16转10:eval(b),eval(o),eval(h)
>>> eval(oct(i))
10
>>> eval(hex(i))
10

3.ASCII码和字符互转

ord(c),chr(i)

>>> ord('a')
97
>>> ord('1')
49
>>> ord('A')
65
>>> chr(1)
'\x01'
>>> chr(2)
'\x02'
>>> chr(99)
'c'

4.dir() 显示对象的方法

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

5.列表反转 ;列表排序

  • l.revers()
    无返回值,直接改变原列表
>>> l1=[1,2,3,4]
>>> l1.reverse()
>>> l1
[4, 3, 2, 1]
  • reversed(l)
    返回值为迭代对象,不会改变原列表。
>>> l2=[1,2,3,4]
>>> reversed(l2)
<list_reverseiterator object at 0x7ff292d83198>
>>> list(reversed(l2)) # 要获取反转的列表必须用list()把迭代对象转成列表
[4, 3, 2, 1]
  • l.sort()
    无返回值,直接改变原列表;无参数,只能升序
>>> l=[2,5,1,4,2]
>>> l.sort()
>>> l
[1, 2, 2, 4, 5]
  • sorted(l)
    返回值是一个倒序的列表,注意与reversed区分,reversed是返回迭代对象。
    并且不改变原列表
>>> l
[1, 2, 2, 4, 5]
>>> sorted(l)
[1, 2, 2, 4, 5]
>>> print(type(sorted(l)))
#<class 'list'>
  • l[::-1]
    用切片的方式倒序输出列表,返回值是一个新的列表,不改变原列表,功能与reversed一样,只是返回值直接就是列表
>>> l
[1, 2, 2, 4, 5]
>>> l[::-1]
[5, 4, 2, 2, 1]
>>> l
[1, 2, 2, 4, 5]

6. 除,取余,取商,四舍五入

  • 除法(/)
>>> 5/2
2.5
  • 取余数(%)
>>> 5%2
1
  • 取商(//)
>>> 5//2
2
  • 同时取商和余数divmod(被除数,除数)
    返回一个元组(商,余数)
>>> divmod(5,2)
(2, 1)
  • 四舍五入round(i)
>>> round(2.3)
2
>>> round(2.5)
2
>>> round(2.6)
3

7.构造一个列表

  • **range(n)返回的是range对象,需要用list()转成列表
>>> l=[pow(x,2) for x in range(10)]
>>> l
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> l2=range(10)
>>> l2
range(0, 10)
>>> l2=list(range(10))
>>> l2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]






最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容