当前位置:   article > 正文

python常用函数的用法_python常用函数总结

{0:d}

python常用函数总结

普通函数

一、输入输出函数

1、print()函数

输出函数

向屏幕输出指定的汉字

print("hello world")

print()函数可以同时输出多个字符串,用逗号“,”隔开

print("hello","how","are","you")

print()会依次打印每个字符串,遇到逗号“,”会输出空格,输出的内容是这样的:

hello how are you

print()可以打印整数,或者计算结果

>>>print(300)

300

>>>print(100 + 200)

300

我们也可以把打印的结果显示的再漂亮一些

>>>print("100 + 200 =", 100 + 200)100 + 200 = 300

注意:对于字符串"100 + 200 ="它会原样输出,但是对于100+200,python解释器自动计算出结果为300,因此会打印出上述的结果。

字符串相加,进行字符串的连接,且不产生空格

print("hello","你好")#使用”,“进行连接

print("he" + "llo")#字符串相加,进行字符串的连接,且不产生空格

print(10+30)#没有使用引号括起来,默认为数值,若是使用引号括起来,就是字符串#若是数值使用加号连接,默认是表达式进行计算,返回计算的结果

print("hello"+1) #会报错#不同类型的数据不能使用加号连接#不同类型的数据能够使用”,“进行连接

print("1 2 3",2+3)#输入#input()#带有提示信息的输入#name = input("请输入您的姓名:")#print(name)

python中print之后是默认换行的

要实现不换行要加end参数表明

n =0while n <= 100:print("n =",n,end=' ')if n == 20:breakn+= 1输出:

n= 0 n = 1 n = 2 n = 3 n = 4 n = 5 n = 6 n = 7 n = 8 n = 9 n = 10 n = 11 n = 12 n = 13 n = 14 n = 15 n = 16 n = 17 n = 18 n = 19 n = 20

多个数值进行比较

print('c'>'b'>'a')print(5>1>2)

输出:

True

False

2、input()函数

输入函数

Python提供了一个input()函数,可以让用户输入字符串,并且存放在变量中,比如输入用户名

>>> name = input()

jean

如何查看输入的内容:

>>> name

'jean'

或者使用:

>>> print(name)

jean

当然,有时候需要友好的提示一下,我们也可以这样做:

>>> name = input("place enter your name")

place input your name jean

>>> print("hello,", name)

hello, jean

二、进制转换函数

1、bin(),oct(),hex()进制转换函数(带前缀)

使用bin(),oct(),hex()进行转换的时候的返回值均为字符串,且带有0b, 0o, 0x前缀.

十进制转换为二进制

>>> bin(10)

'0b1010'

十进制转为八进制

>>> oct(12)

'014'

十进制转为十六进制

>>> hex(12)

'0xc'

2、’{0:b/o/x}’.format()进制转换函数(不带前缀)

十进制转换为二进制

>>>'{0:b}'.format(10)

'1010'

十进制转为八进制

>>> '{0:o}'.format(12)

'14'

十进制转为十六进制

>>> '{0:x}'.format(12)

'c'

注意:hex函数比格式化字符串函数format慢,不推荐使用.

3、int(’’,2/8/16)转化为十进制函数(不带前缀)

二进制转为十进制

>>> int('1010',2)

10

八进制转为十进制

>>> int('014', 8)

12

十六进制转十进制

>>> int('0xc',16)

12

4、’{0:d}’.format()进制转换为十进制函数

二进制转十进制

>>> '{0:d}'.format(0b11)

'3'

八进制转十进制

>>> '{0:d}'.format(0o14)

'12'

十六进制转十进制

>>> '{0:d}'.format(0x1f)

'31'

5、eval()进制转为十进制函数

二进制转十进制

>>> eval('0b11')

'3'

八进制转十进制

>>> eval('0o14')

'12'

十六进制转十进制

>>> eval('0x1f')

'31'

注意:eval函数比int函数慢,不推荐使用

二进制, 十六进制以及八进制之间的转换,可以借助十进制这个中间值,即先转十进制再转其他的进制,也可以直接使用函数进制转换.

#借助十进制

>>> bin(int('fc',16))'0b11111100'

#利用函数直接转

>>> bin(0xa)'0b1010'

>>> oct(0xa)'012'

>>> hex(10)'0xa'

三、求数据类型函数

1、type()

n = "hello world"n=type(n)print(n)

输出:

2、使用type()判断变量的类型

#int float str bool tuple list dict set

str1 = 'ss'

if type(num) ==str:print('yes')

输出:

yes

str1= 'ss'

print(isinstance(str1,str))

输出:

True

推荐使用isinstance()

3、isinstance()

功能:判断变量是否属于某一数据类型,可以判断子类是否属于父类。

classA():pass

classB(A):def __init__(self):

super(B, self).__init__()pass

classC(A):def __init__(self):

A.__init__(self)

n= 0.1

print(isinstance(n,(int,float,str)))print(isinstance(n,int))print(isinstance(A,object))

b=B()print(isinstance(b,A))

c=C()print(isinstance(c,B))

输出:

True

False

True

True

False

四、关键字函数

1、keyword.kwlist()函数

查看关键字 :

importkeywordprint(keyword.kwlist)

输出:

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

五、删除变量/对象函数

1、del() 函数

变量一旦删除,就不能引用,否则会报错

用法1

n = "hello world"

print(n)

del n

用法2

n = "hello world"

print(n)del(n)print(n)

输出:

hello world

NameError: name'n' is not defined

六、数学函数 pandas, munpy

1、abs(num) 返回num的绝对值

print(abs(-3))

输出: 3

2、max(num1,num2,…,numn) 返回给定参数的最大值

num1 = 10num2= 20

print(num1 >num2)print(max(num1,num2,56))

输出:

False56

3、min(num1,num2,…,numn) :返回给定参数的最小值

print(min(12,3,34,0))

输出:

0

4、pow(x,y) : 求x的y次方,x^y

print(pow(2,3))

输出:

8

5、round(num,n) : 四舍五入,

​ 参数一:需要进行四舍五入的数据;

参数二:保留小数的位数。若n不写,默认为0

print(round(123.486,2))

输出:

123.49

六、range()函数

range([start,] stop [,step])

实质:创建了一个可迭代对象;一般情况下与for循环一起连用

1、start 可以不写,默认值是0,若给定则从start开始

2、stop 必须给定;

3、取值范围[start,stop)

4、step:步长,若不给则默认为1

'''需求:使用for循环计算1*2*3...*20的值'''accou= 1

for i in range(1,21):

accou*=iprint(accou)

输出:2432902008176640000

七、字符串函数

1、eval(str)函数

功能:将字符串转成有效的表达式来求值或者计算结果

可以将字符串转化成列表list,元组tuple,字典dict,集合set

注意:生成了一个新的字符串,没有改变原本的字符串

#12-3 --> 9

str1 = "12-3"

print(eval(str1))print(str1)print(eval("[1,2,3,4]"))print(type(eval("[1,2,3,4]")))print(eval("(1,2,3,4)"))print(eval('{1:1,2:2,3:3}'))print(eval('{2,3,5,3}'))

输出:9

12-3[1, 2, 3, 4](1, 2, 3, 4)

{1: 1, 2: 2, 3: 3}

{2, 3, 5}

2、len(str)函数

功能:获取字符串长度

str1 = "you are good man"

print(len(str1))

输出:

16

3、str.lower()函数

功能:返回一个字符串中大写字母转化成小写字母的字符串

注意:生成了一个新的字符串,没有改变原本的字符串

str1 = "You are good Man"

print(str1.lower())print(str1)

输出:

you are good man

You are good Man

4、str.upper()函数

功能:返回一个字符串中小写字母转化成大写字母的字符串

注意:生成了一个新的字符串,没有改变原本的字符串

str1 = "You are good man"

print(str1.upper())print(str1)

输出:

YOU ARE GOOD MAN

You are good man

5、str.swapcase()函数

功能:返回字符串中的大写字母转小写,小写字母转大写的字符串

注意:生成了一个新的字符串,没有改变原本的字符串

str1 = "You are Good man"

print(str1.swapcase())print(str1)

输出:

yOU ARE gOOD MAN

You are Good man

6、str.capitalize()函数

功能:返回字符串中的首字母大写,其余小写的字符串

注意:生成了一个新的字符串,没有改变原本的字符串

tr1 = "you Are good man"

print(str1.capitalize())print(str1)

str2= "You are a good Man"

print(str2.capitalize())

输出:

You are good man

you Are good man

7、str.title()函数

功能:返回一个每个单词首字母都大写的字符串

注意:生成了一个新的字符串,没有改变原本的字符串

str1 = "you Are good man"

print(str1.title())print(str1)

str2= "You are a good Man"

print(str2.title())

输出:

You Are Good Man

you Are good man

You Are A Good Man

8、str.center(width[,fillchar])函数

功能:返回一个指定宽度的居中字符串

参数一:指定的参数【必须有】

参数二:fillchar填充的字符,若未指定,则默认使用空格

注意:生成了一个新的字符串,没有改变原本的字符串

str1 = "you Are good man"

print(str1.center(20,"*"))print(str1)

输出:

you Are good man**you Are good man**you Are good man

9、str.ljust(width[,fillchar])函数

功能:返回一个指定宽度左对齐的字符串

参数一:指定字符串的宽度【必须有】

参数二:填充的字符,若不写则默认为空格

注意:生成了一个新的字符串,没有改变原本的字符串

str1 = "you Are good man"

print(str1.ljust(20,"*"))print(str1)

输出:

you Are good man****you Are good man

10、str.rjust(width[,fillchar])函数

功能:返回一个指定宽度右对齐的字符串

参数一:指定字符串的宽度【必须有】

参数二:填充的字符,若不写则默认为空格

注意:生成了一个新的字符串,没有改变原本的字符串

str1 = "you Are good man"

print(str1.rjust(20,"*"))print(str1)

输出:****you Are good man

you Are good man

11、str.zfill(width)函数

功能:返回一个长度为width的字符串,原字符右对齐,前面补0

注意:生成了一个新的字符串,没有改变原本的字符串

str1 = "you Are good man"

print(str1.zfill(20))

print(str1)

输出:

0000you Are good man

12、str2.count(str1,start,end])函数

功能:返回str1在str2中出现的次数,可以指定一个范围,若不指定则默认查找整个字符串

区分大小写

注意:生成了一个新的字符串,没有改变原本的字符串

str1 = "hello"str2= "Hello hello1 Hello2 hi haha helloa Are good man"

print(str2.count(str1,0,20))

输出:1

13、str2.find(str1,start,end)函数

功能:从左往右检测str2,返回str1第一次出现在str2中的下标

若找不到则返回-1,可以指定查询的范围,若不指定则默认查询整个字符串

注意:生成了一个新的字符串,没有改变原本的字符串

str1 = "hello"str2= "Hello hello1 Hello2 hi haha helloa Are good man"

print(str2.find(str1,5,20))

输出:6

14、str2.rfind(str1,start,end)函数

功能:从右往左检测str2,返回str1第一次出现在str2中的小标,若找不到则返回-1,可以指定查询的范围,若不指定则默认查询整个字符串

注意:生成了一个新的字符串,没有改变原本的字符串

str1 = "hello"str2= "Hello hello1 Hello2 hi haha helloa Are good man"

print(str2.rfind(str1,10,35))

输出;28

15、str2.index(str1,start,end)函数

功能:和find()一样,不同的是若找不到str1,则会报异常

ValueError:substring not found

注意:生成了一个新的字符串,没有改变原本的字符串

str1 = "hello"str2= "Hello hello1 Hello2 hi haha helloa Are good man"

print(str2.index(str1,2,25))print(str2.index(str1,24,25))

输出:6ValueError: substringnot found

16、str.lstrip(char)函数

功能:返回一个截掉字符串左侧指定的字符,若不给参数则默认截掉空字符: \n \r \t 空格

注意:生成了一个新的字符串,没有改变原本的字符串

str3 = "\n\r \t ni hao ma"

print(str3)print(str3.lstrip())

str4= "****ni hao ma****"

print(str4.lstrip('*'))

输出;

ni hao ma

ni hao ma

ni hao ma****

17、str.rstrip()函数

功能:返回一个截掉字符串右侧指定的字符,若不给参数则默认截掉空字符: \n \r \t 空格

注意:生成了一个新的字符串,没有改变原本的字符串

str3 = "ni hao ma \n\r \t"

print(str3.rstrip())

str4= "****ni hao ma****"

print(str4.rstrip('*'))

输出:

ni hao ma****ni hao ma

18、str2.split(str1,num) 分离字符串

功能:返回一个列表,列表的元素是以str1作为分隔符对str2进行切片,

若num有指定值,则切num次,列表元素个数为num+1

若不指定则全部进行切片

若str1不指定,则默认为空字符(空格、换行\n、回车\r、制表\t)

注意:生成了一个新的字符串,没有改变原本的字符串

str2 = "22hello nihao hi hello haha ello2 hello3 hello"

print(str2.split(' ',3))

str3= "1257309054@qq.com"

print(str3.split('@'))

list1= str3.split('@')print(list1[1].split('.'))

输出:

['22hello', 'nihao', 'hi', 'hello haha ello2 hello3 hello']

['1257309054', 'qq.com']

['qq', 'com']

19、str2.splitlines()

功能:返回一个列表,列表的元素是以换行为分隔符,对str2进行切片

注意:生成了一个新的字符串,没有改变原本的字符串

str2 = '''22

23

hello'''

print(str2.splitlines())

输出:

['', '22', '23', 'hello']

20、str1.join(seq)函数 字符串连接

功能:以指定字符串作为分隔符,将seq中的所有元素合并成为一个新的字符串

seq:list、tuple、string

list1 = ["hello","nihao"]print(" ".join(list1))

输出:

hello nihao

str1= "how are you , i am fine thank you"str3= "*".join(str1)print(str3)

输出:

h*o*w* *a*r*e* *y*o*u* *,* *i* *a*m* *f*i*n*e* *t*h*a*n*k* *y*o*u

21、ord() 求字符的ASCLL码值函数

print(ord("a"))

输出:

97

22、chr() 数字转为对应的ASCLL码函数

print(chr(97))

输出:

a

23、 max(str) min(str)获取最大最小字符

**max(str) **功能: 返回字符串str中最大的字母

str1 = "how are you , i am fine thank you"

print(max(str1))

输出:

y

min(str) 功能:返回字符串str中最小字母

str1 = "how are you , i am fine thank you"

print(min(str1))

输出:

' '

24、str.replace(old , new [, count]) 字符串的替换

str.replace(old , new [, count])

功能:使用新字符串替换旧字符串,若不指定count,则默认全部替换,

若指定count,则替换前count个

str1 = "you are a good man"

print(str1.replace("good","nice"))

输出:

you are a nice man

25、字符串映射替换

参数一:要转换的字符 参数二:目标字符

dic = str.maketrans(oldstr, newstr)

str2.translate(dic)

str1 = "you are a good man"dic= str1.maketrans("ya","32")print(str1.translate(dic))

结果:

3ou 2re2 good m2n

26、str.startswith(str1,start.end) 判断字符串的开头

str.startswith(str1,start.end)

功能:判断在指定的范围内字符串str是否以str1开头,若是就返回True,否则返回False

若不指定start,则start默认从开始,

若不指定end,则默认到字符串结尾

str1 = "hello man"

print(str1.startswith("h",0,6))

输出:

True

27、str.endswith(str1,start.end) 判断字符串的结尾

str.endswith(str1,start.end)

功能:判断在指定的范围内字符串str是否以str结束,若是就返回True,否则返回False

若不指定start,则start默认从开始,

若不指定end,则默认到字符串结尾

str1 = "hello man"

print(str1.endswith("man"))

输出:

True

28、str.encode(编码格式)

对字符串进行编码 默认是utf-8

编码:str.encode()

解码:str.encode().decode()

注意:encode()的编码格式与decode()的编码格式必须保持一致

str4 = "你好吗"

print(str4.encode())print(str4.encode().decode())print(str4.encode("gbk"))print(str4.encode("gbk").decode("gbk"))

输出:

b'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97'你好吗

b'\xc4\xe3\xba\xc3\xc2\xf0'你好吗

29、str1.isalpha() 字符串为字母

功能:判断字符串【至少含有一个字符】中的所有的字符是否都是字母【a~z A~Z 汉字】

若符合条件则返回True,否则返回False

str5 = "hello你二"

print(str5.isalpha())

str5= "hello"

print(str5.isalpha())

输出:

True

False

30、str5.isalnum()

功能:判断字符串【至少含有一个字符】中的所有字符都是字母或者数字【09,Az,中文】

str5 = "helloA标红"

print(str5.isalnum())print("12aaa".isalnum())print("aaa".isalnum())print("111".isalnum())print("111".isalnum())print("$$%%qwqw11".isalnum())print("你好".isalnum())print( "IV".isalnum())print('Ⅳ'.isalnum())

输出;

True

True

True

False

True

False

True

True

True

31、str.isupper()

功能:判断字符串中所有字符是不是大写字符

print("WWW".isupper())print("wWW".isupper())print("123".isupper())print("一二三".isupper())

输出;

True

False

False

False

31、str.islower()

功能:判断字符串中所有字符是不是小写字符

print("WWW".islower())print("wWW".islower())print("123".islower())print("一二三".islower())print("qwww".islower())

输出:

False

False

False

False

True

32、str.istitle()

功能:判断字符串是否是标题化字符串【每个首字母大写】

print("U Wss".istitle())print("wWW".istitle())print("123".istitle())print("一二三".istitle())print("qwww".istitle())

输出:

True

False

False

False

False

33、 str.isdigit()

isdigit()

True: Unicode数字,byte数字(单字节),全角数字(双字节)

False: 汉字数字, ,罗马数字

Error: 无

print("123".isdigit())print("123".isdigit())print(b"1".isdigit())print("Ⅳ".isdigit())print("123.34".isdigit())print("一".isdigit())

输出;

True

True

True

False

False

False

34、str.isspace()

功能:判断字符串中是否只含有空格

print("ddd".isspace())print("".isspace())print("a ddd".isspace())print("aaa".isspace())print(" ".isspace())

输出;

False

False

False

False

True

35、str.isnumeric()

功能:若字符串中只包含数字字符,则返回True,否则返回False

isnumeric()

True: Unicode数字,全角数字(双字节),汉字数字

False: 罗马数字,

Error: byte数字(单字节)

36、str.isdecimal()

功能:检查字符串是否只包含十进制字符【0,9】,如果是返回True,否则返回False

isdecimal()

True: Unicode数字,,全角数字(双字节),

False: 罗马数字,汉字数字

Error: byte数字(单字节)

print("123".isdecimal())

print("123z".isdecimal())

#结果

True

False

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号