search
HomeBackend DevelopmentPython TutorialPython入门及进阶笔记 Python 内置函数小结

内置函数
常用函数

1.数学相关
•abs(x)
abs()返回一个数字的绝对值。如果给出复数,返回值就是该复数的模。

复制代码 代码如下:

>>>print abs(-100)
100
>>>print abs(1+2j)
2.2360679775

•divmod(x,y)
divmod(x,y)函数完成除法运算,返回商和余数。

复制代码 代码如下:

>>> divmod(10,3)
(3, 1)
>>> divmod(9,3) (3, 0)

•pow(x,y[,z])
pow()函数返回以x为底,y为指数的幂。如果给出z值,该函数就计算x的y次幂值被z取模的值。

复制代码 代码如下:

>>> print pow(2,4)
16
>>> print pow(2,4,2)
0
>>> print pow(2.4,3)
13.824

•round(x[,n])
round()函数返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。

复制代码 代码如下:

>>> round(3.333)
3.0
>>> round(3)
3.0
>>> round(5.9)
6.0

•min(x[,y,z...])
min()函数返回给定参数的最小值,参数可以为序列。

复制代码 代码如下:

>>> min(1,2,3,4)
1
>>> min((1,2,3),(2,3,4))
(1, 2, 3)

•max(x[,y,z...])
max()函数返回给定参数的最大值,参数可以为序列。

复制代码 代码如下:

>>> max(1,2,3,4)
4
>>> max((1,2,3),(2,3,4))
(2, 3, 4)

2.序列相关

•len(object) -> integer
len()函数返回字符串和序列的长度。

复制代码 代码如下:

>>> len("aa")
2
>>> len([1,2])
2

•range([lower,]stop[,step])
range()函数可按参数生成连续的有序整数列表。

复制代码 代码如下:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10,2)
[1, 3, 5, 7, 9]

•xrange([lower,]stop[,step])
xrange()函数与range()类似,但xrnage()并不创建列表,而是返回一个xrange对象,它的行为

与列表相似,但是只在需要时才计算列表值,当列表很大时,这个特性能为我们节省内存。

复制代码 代码如下:

>>> a=xrange(10)
>>> print a[0]
0
>>> print a[1]
1
>>> print a[2]
2

3.对象及类型
•callable(object)
callable()函数用于测试对象是否可调用,如果可以则返回1(真);否则返回0(假)。可调用对象包括函数、方法、代码对象、类和已经定义了 调用 方法的类实例。

复制代码 代码如下:

>>> a="123"
>>> print callable(a)
False
>>> print callable(chr)
True

•cmp(x,y)
cmp()函数比较x和y两个对象,并根据比较结果返回一个整数,如果xy,则返回1,如果x==y则返回0。

复制代码 代码如下:

>>>a=1
>>>b=2
>>>c=2
>>> print cmp(a,b)
-1
>>> print cmp(b,a)
1
>>> print cmp(b,c)
0

•isinstance(object,class-or-type-or-tuple) -> bool
测试对象类型

复制代码 代码如下:

>>> a='isinstance test'
>>> b=1234
>>> isinstance(a,str)
True
>>>isinstance(a,int)
False
>>> isinstance(b,str)
False
>>> isinstance(b,int) True

•type(obj)
type()函数可返回对象的数据类型。

复制代码 代码如下:

>>> type(a)

>>> type(copy)

>>> type(1)

内置类型转换函数

1.字符及字符串
•chr(i)
chr()函数返回ASCII码对应的字符串。

复制代码 代码如下:

>>> print chr(65)
A
>>> print chr(66)
B
>>> print chr(65)+chr(66)
AB

•ord(x)
ord()函数返回一个字符串参数的ASCII码或Unicode值。

复制代码 代码如下:

>>> ord("a")
97
>>> ord(u"a")
97

•str(obj)
str()函数把对象转换成可打印字符串。

复制代码 代码如下:

>>> str("4")
'4'
>>> str(4)
'4'
>>> str(3+2j)
'(3+2j)'

2.进制转换
•int(x[,base])
int()函数把数字和字符串转换成一个整数,base为可选的基数。

复制代码 代码如下:

>>> int(3.3)
3
>>> int(3L)
3
>>> int("13")
13
>>> int("14",15)
19

•long(x[,base])
long()函数把数字和字符串转换成长整数,base为可选的基数。

复制代码 代码如下:

>>> long("123")
123L
>>> long(11)
11L

•float(x)
float()函数把一个数字或字符串转换成浮点数。

复制代码 代码如下:

>>> float("12")
12.0
>>> float(12L)
12.0
>>> float(12.2)
12.199999999999999

•hex(x)
hex()函数可把整数转换成十六进制数。

复制代码 代码如下:

>>> hex(16)
'0x10'
>>> hex(123)
'0x7b'

•oct(x)
oct()函数可把给出的整数转换成八进制数。

复制代码 代码如下:

>>> oct(8)
'010'
>>> oct(123)
'0173'

•complex(real[,imaginary])
complex()函数可把字符串或数字转换为复数。

复制代码 代码如下:

>>> complex("2+1j")
(2+1j)
>>> complex("2")
(2+0j)
>>> complex(2,1)
(2+1j)
>>> complex(2L,1)
(2+1j)

3.数据结构
•tuple(x)
tuple()函数把序列对象转换成tuple。

复制代码 代码如下:

>>> tuple("hello world")
('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
>>> tuple([1,2,3,4])
(1, 2, 3, 4)

•list(x)
list()函数可将序列对象转换成列表。如:

复制代码 代码如下:

>>> list("hello world")
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> list((1,2,3,4))
[1, 2, 3, 4]

序列处理函数
常用函数中的len()、max()和min()同样可用于序列。

•filter(function,list)
调用filter()时,它会把一个函数应用于序列中的每个项,并返回该函数返回真值时的所有项,从而过滤掉返回假值的所有项。

复制代码 代码如下:

>>> def nobad(s):
    ... return s.find("bad") == -1
    ...
>>> s = ["bad","good","bade","we"]
>>> filter(nobad,s)
['good', 'we']

•map(function,list[,list])
map()函数把一个函数应用于序列中所有项,并返回一个列表。

复制代码 代码如下:

>>> import string
>>> s=["python","zope","linux"]
>>> map(string.capitalize,s)
['Python', 'Zope', 'Linux']

map()还可同时应用于多个列表。如:

复制代码 代码如下:

>>> import operator
>>> s=[1,2,3]; t=[3,2,1]
>>> map(operator.mul,s,t) # s[i]*t[j]
[3, 4, 3]

如果传递一个None值,而不是一个函数,则map()会把每个序列中的相应元素合并起来,并返回该元组。如:

复制代码 代码如下:

>>> a=[1,2];b=[3,4];c=[5,6]
>>> map(None,a,b,c)
[(1, 3, 5), (2, 4, 6)]

•reduce(function,seq[,init])
reduce()函数获得序列中前两个项,并把它传递给提供的函数,获得结果后再取序列中的下一项,连同结果再传递给函数,以此类推,直到处理完所有项为止。

[code]
>>> import operator
>>> reduce(operator.mul,[2,3,4,5]) # ((2*3)*4)*5
120
>>> reduce(operator.mul,[2,3,4,5],1) # (((1*2)*3)*4)*5
120
>>> reduce(operator.mul,[2,3,4,5],2) # (((2*2)*3)*4)*5
240
[code]

wklken
Email: wklken@yeah.net

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.