查看对象类型的python内置函数_python的内置函数 剖析

内置方法:

1.  abs()       #取绝对值;

>>> abs(-11)

11

>>> abs(11)

11

2. all        #非0即真,确保所有元素为真才为真;

>>> all([0, -5, 3])

False

>>> all([1, -5, 3])

True

3. any        #非0即真,确保一个元素为真就为真;

>>> any([0, -5, 3])

True

>>> any([1, -5, 3])

True

>>> any([0,0])

False

4. ascii()       #将内存对象转变为一个可打印的字符形式

>>> ascii("abcd")

"‘abcd‘"

>>> ascii("abcd111")

"‘abcd111‘"

>>> ascii(1)

‘1‘

>>> ascii([1,2])

‘[1, 2]‘

5. bin()       #将十进制数字转换二进制

>>> bin(8)

‘0b1000‘

>>> bin(19)

‘0b10011‘

>>>

6. bool():       #判断是否真,空列表等都为假false

>>> bool([])

False

>>> bool([1,2])

True

>>>

7. bytearray()      #把字符变成asscii可以更改;

>>> b = bytearray("abdcd", encoding="utf-8")

>>>

>>> print(b[0])

97

>>> print(b[1])

98

>>> b[1]=100

>>> print(b)

bytearray(b‘addcd‘)

a = bytes("abdcd")

>>> a

b‘abdcd

8. chr()       #将ascii值转为对应的字符。

>>> chr(90)

‘Z‘

9. ord()       #将字符转为ascii

>>> ord("a")

97

>>> ord("Z")

90

10. complie()      #简单的编译反执行。   可以用 exec可以执行字符串源码;

>>> code = "for i in range(10):print(i)"

>>> code

‘for i in range(10):print(i)‘

>>>

>>> compile(code,"","exec")

at 0x00B540D0, file "", line 1>

>>>

>>> c = compile(code,"","exec")

>>> exec(c)

0

1

2

3

4

5

6

7

8

9

>>>

11. dir()       #查看对象的方法:

>>> dir({})

[‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘clear‘, ‘copy‘, ‘fromkeys‘, ‘get‘, ‘items‘, ‘keys‘, ‘pop‘, ‘popitem‘, ‘setdefault‘, ‘update‘, ‘values‘]

>>> dir([])

[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__iadd__‘, ‘__imul__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__reversed__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘append‘, ‘clear‘, ‘copy‘, ‘count‘, ‘extend‘, ‘index‘, ‘insert‘, ‘pop‘, ‘remove‘, ‘reverse‘, ‘sort‘]

>>>

12. divmod()      #返回商和余数

>>> divmod(5,1)

(5, 0)

>>> divmod(5,2)

(2, 1)

>>> divmod(5,3)

(1, 2)

>>>

13. enumerate():     #

>>> sersons = ["Spring","Summer","Autron","Wintor"]

>>>

>>> list(enumerate(sersons))

[(0, ‘Spring‘), (1, ‘Summer‘), (2, ‘Autron‘), (3, ‘Wintor‘)]

>>>

>>> list(enumerate(sersons, start=1))

[(1, ‘Spring‘), (2, ‘Summer‘), (3, ‘Autron‘), (4, ‘Wintor‘)]

>>>

>>>

>>> for k,v in enumerate(sersons, start=1):print("%d--%s"% (k, v))

...

1--Spring

2--Summer

3--Autron

4--Wintor

>>>

14. eval()     #将字符串转为数据类型,不能有语句的,有语句的用exec

>>> x = "[1,2,3,4]"

>>> x

‘[1,2,3,4]‘

>>>

>>> x[0]

‘[‘

>>>

>>> y = eval(x)

>>> y

[1, 2, 3, 4]

>>> y[0]

1

>>>

15. exec()        #  执行字符串源码

>>> x = "for i in range(10):print(i)"

>>> x

‘for i in range(10):print(i)‘

>>>

>>>

>>> exec(x)

0

1

2

3

4

5

6

7

8

9

>>>

16. filter():          #按条件进行过滤

>>> x = filter(lambda n:n>5, range(10))

>>> for i in x:print(i)

...

6

7

8

9

将后面的值拿出来给前面处理

>>> x = map(lambda n:n*n, range(10))   #按照范围的输出, 相当于:x = [lambda n:n*n for i in range(10)]

>>> for i in x:print(i)

...

0

1

4

9

16

25

36

49

64

81

匿名函数:只能处理3月运算

>>> lambda n:print(n)

at 0x0368BDB0>

>>>

>>> (lambda n:print(n))(5)

5

>>>

>>> x=lambda n:print(n)

>>> x(5)

5

>>> lambda m:m*2

at 0x03716198>

>>> y=lambda m:m*2

>>> y(5)

10

>>>

>>> z = lambda n:3 if n<4 else n

>>> z(2)

3

>>> z(5)

5

17. frozenset()     #集合冻结,后即不可修改

>>> a=set([12,2,12,12,12,12])

>>> a

{2, 12}

>>> a.add(13)

>>> a

{2, 12, 13}

>>>

>>> b = frozenset(a)

>>> b

frozenset({2, 12, 13})

>>>

>>>

>>> b.add(3)

Traceback (most recent call last):

File "", line 1, in

AttributeError: ‘frozenset‘ object has no attribute ‘add‘

>>>

18. globals()      #返回整个程序所有的全局变量值:

>>> globals()

{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: , ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: , ‘Iterable‘: , ‘Iterator‘: , ‘x‘: , ‘a‘: {2, 12, 13}, ‘b‘: frozenset({2, 12, 13}), ‘code‘: ‘for i in range(10):print(i)‘, ‘c‘: at 0x00B54128, file "", line 1>, ‘i‘: 81, ‘sersons‘: [‘Spring‘, ‘Summer‘, ‘Autron‘, ‘Wintor‘], ‘k‘: 4, ‘v‘: ‘Wintor‘, ‘y‘: at 0x036AB6A8>, ‘z‘: at 0x03716150>}

>>>

19. hash()       # 返回hash值;

>>> hash("1")

-585053941

>>>

>>> hash("qwqw")

1784621666

>>>

19.  hex()       #抓16进制

>>> hex(100)

‘0x64‘

>>> hex(15)

‘0xf‘

>>>

20. oct()      #转为8进制

>>> oct(10)

‘0o12‘

21.  locals()      #打印本地变量;

>>> locals()

{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: , ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: , ‘Iterable‘: , ‘Iterator‘: , ‘x‘: , ‘a‘: {2, 12, 13}, ‘b‘: frozenset({2, 12, 13}), ‘code‘: ‘for i in range(10):print(i)‘, ‘c‘: at 0x00B54128, file "", line 1>, ‘i‘: 81, ‘sersons‘: [‘Spring‘, ‘Summer‘, ‘Autron‘, ‘Wintor‘], ‘k‘: 4, ‘v‘: ‘Wintor‘, ‘y‘: at 0x036AB6A8>, ‘z‘: at 0x03716150>}

>>>

21. max():      #返回最大值

>>> max([1,2,3,4,5])

5

23. min():      #返回最小值

>>> min([1,2,3,4,5])

1

24. pow(x,y)      #返回多次幂,x的y次方

>>> pow(2,2)

4

>>> pow(2,3)

8

25. range(start,stop,step)

26. repr()       #用字符串表示一个对对象:

27. reversed(seq)     #反转

28. round()       #浮点数按照规定四舍五入舍弃,

>>> round(1.232442)

1

>>> round(1.232442,2)

1.23

>>> round(1.237442,2)

1.24

>>>

29. id()         #取内存id值

>>> id("1")

56589120

>>> id("a")

56501888

30. sorted(iterable[,key][,reverse])  #排序

>>> a = {5:1,9:2,1:3,8:4,3:9}

>>>

>>> sorted(a)

[1, 3, 5, 8, 9]

>>> sorted(a.items())

[(1, 3), (3, 9), (5, 1), (8, 4), (9, 2)]

>>> sorted(a.items(),key=lambda x:x[1])

[(5, 1), (9, 2), (1, 3), (8, 4), (3, 9)]

>>> a.items()       #将字典转化为列表。

dict_items([(5, 1), (9, 2), (1, 3), (8, 4), (3, 9)])

>>>

>>> list(a)

[5, 9, 1, 8, 3]

31. sum(iterable[,start])     #求和,start为sum初始值

>>> sum([1, 3, 5, 8, 9])

26

>>> sum([1, 3, 5, 8, 9],3)

29

>>> sum([1, 3, 5, 8, 9],30)

56

32. tuple(iterable):      #转化为元组

>>> tuple([1, 3, 5, 8, 9])

(1, 3, 5, 8, 9)

34. zip()         #中文就是拉链的意思,一一对应

>>> a = (1, 3, 5, 8, 9)

>>> b = ("a","b","c","d","e")

>>>

>>> zip(a,b)

>>> for n in zip(a,b):

...   print(n)

...

(1, ‘a‘)

(3, ‘b‘)

(5, ‘c‘)

(8, ‘d‘)

(9, ‘e‘)

>>>

35. __import__("模块名")     #只知道模块名时导入模块就方法:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中提供了很多字符串内置函数,这里列举几个比较常用的: 1. `len(str)`:返回字符串的长度。 ```python str = "hello, world!" print(len(str)) # 输出:13 ``` 2. `str.upper()`和`str.lower()`:将字符串分别转化为大写和小写形式。 ```python str = "Hello, WoRlD!" print(str.upper()) # 输出:HELLO, WORLD! print(str.lower()) # 输出:hello, world! ``` 3. `str.capitalize()`和`str.title()`:将字符串的首字母或每个单词的首字母转化为大写。 ```python str = "hello, world!" print(str.capitalize()) # 输出:Hello, world! print(str.title()) # 输出:Hello, World! ``` 4. `str.find(sub, start, end)`和`str.index(sub, start, end)`:返回子字符串在原字符串中的位置,若没有则返回-1或抛出异常。 ```python str = "hello, world!" print(str.find('o')) # 输出:4 print(str.index('o')) # 输出:4 print(str.find('z')) # 输出:-1 # print(str.index('z')) # 抛出异常:ValueError: substring not found ``` 5. `str.count(sub, start, end)`:返回子字符串在原字符串中出现的次数。 ```python str = "hello, world!" print(str.count('o')) # 输出:2 ``` 6. `str.replace(old, new, count)`:将字符串中的所有旧子字符串替换为新子字符串,count为替换次数,可省略,表示替换所有。 ```python str = "hello, world!" print(str.replace('l', 'L')) # 输出:heLLo, worLd! ``` 除此之外,还有很多其他的字符串内置函数,比如`str.startswith(prefix, start, end)`、`str.endswith(suffix, start, end)`、`str.strip(chars)`、`str.join(iterable)`等等。这些函数都有其特定的功能和用法,可以根据实际情况进行选择和使用。 引用:Python字符串内置函数功能与用法总结。主要介绍了Python字符串内置函数功能与用法,结合实例形式总结分析了Python常见字符串操作函数的功能、分类、使用方法及相关操作注意事项,需要的朋友可以参考下[^1]。 引用:python string内置函数表格。string.replace(str1, str2, num=string.count(str1)) [^2]。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值