关于数据分类依据

一、数字型(int)

  Python可以处理任意大小的正负整数,但是实际中跟我们计算机的内存有关,在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1。对于int类型,需要掌握的方法不多,看下面的几个例子:

Number 类型转换

语法 描述
int(x [,base ])
 将x转换为一个整数
long(x [,base ])

将x转换为一个长整数

float(x )
 将x转换到一个浮点数
complex(real [,imag ])
 创建一个复数
str(x )
 将对象 x 转换为字符串
repr(x )
 将对象 x 转换为表达式字符串
eval(str )
 用来计算在字符串中的有效Python表达式,并返回一个对象
tuple(s )
 将序列 s 转换为一个元组
list(s )
 将序列 s 转换为一个列表
chr(x )
 将一个整数转换为一个字符
unichr(x )
 将一个整数转换为Unicode字符
ord(x )
 将一个字符转换为它的ascii码
hex(x )
 将一个整数转换为一个十六进制字符串
oct(x )
 将一个整数转换为一个八进制字符串
 
 
 

数字方法

方法名 描述 语法 参数
abs() 返回数字的绝对值
abs( x )
x -- 数值表达式
print "abs(-45) : ", abs(-45)
print "abs(100.12) : ", abs(100.12)
print "abs(119L) : ", abs(119L) '''
abs(-45) : 45
abs(100.12) : 100.12
abs(119L) : 119 '''
ceil()

返回数字的上入整数,类似高斯函数

需要导入 math 模块,通过静态对象调用该方法

import math

math.ceil( x )
x -- 数值表达式
import math   # This will import math module

print "math.ceil(-45.17) : ", math.ceil(-45.17)
print "math.ceil(100.12) : ", math.ceil(100.12)
print "math.ceil(100.72) : ", math.ceil(100.72)
print "math.ceil(119L) : ", math.ceil(119L)
print "math.ceil(math.pi) : ", math.ceil(math.pi) '''
math.ceil(-45.17) : -45.0
math.ceil(100.12) : 101.0
math.ceil(100.72) : 101.0
math.ceil(119L) : 119.0
math.ceil(math.pi) : 4.0 '''
exp()

返回x的指数 -> ex

需要导入 math 模块,通过静态对象调用该方法

import math

math.exp( x )
x -- 数值表达式
import math   # 导入 math 模块

print "math.exp(-45.17) : ", math.exp(-45.17)
print "math.exp(100.12) : ", math.exp(100.12)
print "math.exp(100.72) : ", math.exp(100.72)
print "math.exp(119L) : ", math.exp(119L)
print "math.exp(math.pi) : ", math.exp(math.pi) '''
math.exp(-45.17) : 2.41500621326e-20
math.exp(100.12) : 3.03084361407e+43
math.exp(100.72) : 5.52255713025e+43
math.exp(119L) : 4.7978133273e+51
math.exp(math.pi) : 23.1406926328 '''
fabs()

返回数字的绝对值

需要导入 math 模块,通过静态对象调用该方法

import math

math.fabs( x )
x -- 数值表达式
import math   # 导入数学模块

print "math.fabs(-45.17) : ", math.fabs(-45.17)
print "math.fabs(100.12) : ", math.fabs(100.12)
print "math.fabs(100.72) : ", math.fabs(100.72)
print "math.fabs(119L) : ", math.fabs(119L)
print "math.fabs(math.pi) : ", math.fabs(math.pi) '''
math.fabs(-45.17) : 45.17
math.fabs(100.12) : 100.12
math.fabs(100.72) : 100.72
math.fabs(119L) : 119.0
math.fabs(math.pi) : 3.14159265359 '''
floor()

返回数字的下舍整数,与ceil相反

需要导入 math 模块,通过静态对象调用该方法

import math

math.floor( x )
x -- 数值表达式
import math   # This will import math module

print "math.floor(-45.17) : ", math.floor(-45.17)
print "math.floor(100.12) : ", math.floor(100.12)
print "math.floor(100.72) : ", math.floor(100.72)
print "math.floor(119L) : ", math.floor(119L)
print "math.floor(math.pi) : ", math.floor(math.pi) '''
math.floor(-45.17) : -46.0
math.floor(100.12) : 100.0
math.floor(100.72) : 100.0
math.floor(119L) : 119.0
math.floor(math.pi) : 3.0 '''
log()

返回 x 的自然对数

需要导入 math 模块,通过静态对象调用该方法

import math

math.log(x[, base])

x -- 数值表达式。

base -- 可选底数,默认为 e

import math   # 导入 math 模块

print "math.log(100.12) : ", math.log(100.12)
print "math.log(100.72) : ", math.log(100.72)
print "math.log(119L) : ", math.log(119L)
print "math.log(math.pi) : ", math.log(math.pi)
# 设置底数
print "math.log(10,2) : ", math.log(10,2) '''
math.log(100.12) : 4.60636946656
math.log(100.72) : 4.61234438974
math.log(119L) : 4.77912349311
math.log(math.pi) : 1.14472988585
math.log(10,2) : 3.32192809489 '''
log10()

返回以10为基数的x对数

需要导入 math 模块,通过静态对象调用该方法

import math

math.log10( x )
x -- 数值表达式
print "math.log10(100.12) : ", math.log10(100.12)
print "math.log10(100.72) : ", math.log10(100.72)
print "math.log10(119L) : ", math.log10(119L)
print "math.log10(math.pi) : ", math.log10(math.pi) '''
math.log10(100.12) : 2.00052084094
math.log10(100.72) : 2.0031157171
math.log10(119L) : 2.07554696139
math.log10(math.pi) : 0.497149872694 '''
max() 返回给定参数的最大值,参数可以为序列
max( x, y, z, .... )

x -- 数值表达式

y -- 数值表达式

z -- 数值表达式

print "max(80, 100, 1000) : ", max(80, 100, 1000)
print "max(-20, 100, 400) : ", max(-20, 100, 400)
print "max(-80, -20, -10) : ", max(-80, -20, -10)
print "max(0, 100, -400) : ", max(0, 100, -400) '''
max(80, 100, 1000) : 1000
max(-20, 100, 400) : 400
max(-80, -20, -10) : -10
max(0, 100, -400) : 100 '''
min() 返回给定参数的最小值,参数可以为序列
min( x, y, z, .... )

x -- 数值表达式

y -- 数值表达式

z -- 数值表达式

print "min(80, 100, 1000) : ", min(80, 100, 1000)
print "min(-20, 100, 400) : ", min(-20, 100, 400)
print "min(-80, -20, -10) : ", min(-80, -20, -10)
print "min(0, 100, -400) : ", min(0, 100, -400) '''
min(80, 100, 1000) : 80
min(-20, 100, 400) : -20
min(-80, -20, -10) : -80
min(0, 100, -400) : -400 '''
modf()

返回x的整数部分与小数部分

两部分的数值符号与x相同,整数部分以浮点型表示

导入 math 模块,通过静态对象调用该方法

import math

math.modf( x )
x -- 数值表达式
import math   # This will import math module

print "math.modf(100.12) : ", math.modf(100.12)
print "math.modf(100.72) : ", math.modf(100.72)
print "math.modf(119L) : ", math.modf(119L)
print "math.modf(math.pi) : ", math.modf(math.pi) '''
math.modf(100.12) : (0.12000000000000455, 100.0)
math.modf(100.72) : (0.71999999999999886, 100.0)
math.modf(119L) : (0.0, 119.0)
math.modf(math.pi) : (0.14159265358979312, 3.0) '''
pow()

返回 xy(x的y次方) 的值

导入 math 模块,通过静态对象调用该方法

import math

math.pow( x, y )

x -- 数值表达式

y -- 数值表达式

import math   # 导入 math 模块

print "math.pow(100, 2) : ", math.pow(100, 2)
# 使用内置,查看输出结果区别
print "pow(100, 2) : ", pow(100, 2) print "math.pow(100, -2) : ", math.pow(100, -2)
print "math.pow(2, 4) : ", math.pow(2, 4)
print "math.pow(3, 0) : ", math.pow(3, 0) '''
math.pow(100, 2) : 10000.0
pow(100, 2) : 10000
math.pow(100, -2) : 0.0001
math.pow(2, 4) : 16.0
math.pow(3, 0) : 1.0 '''
round() 返回浮点数x的四舍五入值
round( x [, n]  )

x -- 数值表达式

n -- 数值表达式

print "round(80.23456, 2) : ", round(80.23456, 2)
print "round(100.000056, 3) : ", round(100.000056, 3)
print "round(-100.000056, 3) : ", round(-100.000056, 3) round(80.23456, 2) : 80.23
round(100.000056, 3) : 100.0
round(-100.000056, 3) : -100.0
 sqrt()

返回数字x的平方根

需要导入 math 模块,通过静态对象调用该方法

import math

math.sqrt( x )
x -- 数值表达式
import math   # This will import math module

print "math.sqrt(100) : ", math.sqrt(100)
print "math.sqrt(7) : ", math.sqrt(7)
print "math.sqrt(math.pi) : ", math.sqrt(math.pi) '''
math.sqrt(100) : 10.0
math.sqrt(7) : 2.64575131106
math.sqrt(math.pi) : 1.77245385091 '''

随机数函数

方法名 描述 语法 参数
choice()

返回一个列表,元组或字符串的随机项

需要导入 random 模块,然后通过 random 静态对象调用该方法

import random

random.choice( seq  )
seq -- 可以是一个列表,元组或字符串
import random

print ("从 range(100) 返回一个随机数 : ",random.choice(range(100)))
print ("从列表中 [1, 2, 3, 5, 9]) 返回一个随机元素 : ", random.choice([1, 2, 3, 5, 9]))
print ("从字符串中 'Runoob' 返回一个随机字符 : ", random.choice('Runoob')) '''
从 range(100) 返回一个随机数 : 68
从列表中 [1, 2, 3, 5, 9]) 返回一个随机元素 : 2
从字符串中 'Runoob' 返回一个随机字符 : u '''
randrange()

返回指定递增基数集合中的一个随机数,基数默认值为1

需要导入 random 模块,然后通过 random 静态对象调用该方法。

import random

random.randrange ([start,] stop [,step])

start -- 指定范围内的开始值,包含在范围内。

stop -- 指定范围内的结束值,不包含在范围内。

step -- 指定递增基数。

import random

# 从 1-100 中选取一个奇数
print ("randrange(1,100, 2) : ", random.randrange(1, 100, 2)) # 从 0-99 选取一个随机数
print ("randrange(100) : ", random.randrange(100)) '''
randrange(1,100, 2) : 97
randrange(100) : 42 '''
random()

在[0,1)范围内,随机生成的一个实数

需要导入 random 模块,然后通过 random 静态对象调用该方法

import random

random.random()
import random

# 第一个随机数
print ("random() : ", random.random()) # 第二个随机数
print ("random() : ", random.random()) '''
random() : 0.09690599908884856
random() : 0.8732120512570916 '''
 seed()

改变随机数生成器的种子,可以在调用其他随机模块函数之前调用此函数

需要导入 random 模块,然后通过 random 静态对象调用该方法

import random

random.seed ( [x] )

x -- 改变随机数生成器的种子seed

如果你不了解其原理,你不必特别去设定seed,Python会帮你选择seed

import random

random.seed()
print ("使用默认种子生成随机数:", random.random())
print ("使用默认种子生成随机数:", random.random()) random.seed(10)
print ("使用整数 10 种子生成随机数:", random.random())
random.seed(10)
print ("使用整数 10 种子生成随机数:", random.random()) random.seed("hello",2)
print ("使用字符串种子生成随机数:", random.random()) '''
使用默认种子生成随机数: 0.7908102856355441
使用默认种子生成随机数: 0.81038961519195
使用整数 10 种子生成随机数: 0.5714025946899135
使用整数 10 种子生成随机数: 0.5714025946899135
使用字符串种子生成随机数: 0.3537754404730722 '''
shuffle()

将序列的所有元素随机排序

需要导入 random 模块,然后通过 random 静态对象调用该方法

import random

random.shuffle (lst )

lst -- 列表
import random

list = [20, 16, 10, 5];
random.shuffle(list)
print ("随机排序列表 : ", list) random.shuffle(list)
print ("随机排序列表 : ", list) '''
随机排序列表 : [20, 5, 16, 10]
随机排序列表 : [5, 20, 10, 16] '''
uniform()

随机生成下一个实数,它在 [x,y] 范围内

需要导入 random 模块,然后通过 random 静态对象调用该方法

import random

random.uniform(x, y)

x -- 随机数的最小值

y -- 随机数的最大值

import random

print ("uniform(5, 10) 的随机浮点数 : ",  random.uniform(5, 10))

print ("uniform(7, 14) 的随机浮点数 : ",  random.uniform(7, 14))

'''
uniform(5, 10) 的随机浮点数 : 7.054602800254241
uniform(7, 14) 的随机浮点数 : 12.552229882744296 '''
 
 

二、字符串(str)

字符串系列的小函数有很多,以下暂列几个

字符串方法

方法名         描述 语法 参数
 capitalize() 

将字符串的第一个字母变成大写,其他字母变小写该方法。

返回一个首字母大写的字符串

s.capitalize()

 1 >>>s = 'a, B'
2 >>> s.capitalize()
3 'A, b'
4
5 >>> s = ' a, B' # a 前面有空格
6 >>> s.capitalize()
7 ' a, b'
8
9 >>> s = 'a, BCD'
10 >>> s.capitalize()
11 'A, bcd'
center()  

原字符串居中,并使用空格填充至长度 width 的新字符串。

默认填充字符为空格。

s.center(width[, fillchar])
width -- 字符串的总宽度

fillchar -- 填充字符

1 >>>str = 'runoob'
2 >>> str.center(20, '*')
3
4 '*******runoob*******'
5
6
7 >>> str.center(20)
8
9 ' runoob '
count()

用于统计字符串里某个字符出现的次数。

可选参数为在字符串搜索的开始与结束位置。

s.count(sub, start= 0,end=len(string))
 sub -- 搜索的子字符串

start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0

end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置

1 >>>str = 'national day'
2 >>>str.count('a',2,20)
3
4 2
decode()

encoding 指定的编码格式解码字符串。

默认编码为字符串编码。

   s.decode(encoding='UTF-8',errors='strict')

encoding -- 要使用的编码,如"UTF-8"

errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值

1 >>>str = "this is string example....wow!!!"
2 >>>str = str.encode('base64','strict')
3
4 >>>print "Encoded String: " + str
5 >>>print "Decoded String: " + str.decode('base64','strict')
6
7 Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=
8 Decoded String: this is string example....wow!!!
encode()

以 encoding 指定的编码格式编码字符串。

errors参数可以指定不同的错误处理方案。

 s.encode(encoding='UTF-8',errors='strict')

 encoding -- 要使用的编码,如"UTF-8"

errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值

1 >>>str = "this is string example....wow!!!"
2
3 >>>print ("Encoded String: " + str.encode('base64','strict'))
4
5 Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=
endswith()

判断字符串是否以指定后缀结尾,如果是则返回True,否则返回False

可选参数"start"与"end"为检索字符串的开始与结束位置。

s.endswith(suffix[, start[, end]])
 suffix -- 该参数可以是一个字符串或者是一个元素

start -- 字符串中的开始位置

end -- 字符中结束位置

 1 >>>str = "this is string example....wow!!!"
2 >>>suffix = "wow!!!"
3
4 >>>print(str.endswith(suffix))
5 >>>print(str.endswith(suffix,20))
6
7 >>>suffix = "is"
8 >>>print(str.endswith(suffix, 2, 4))
9 >>>print(str.endswith(suffix, 2, 6))
10
11 True
12 True
13 True
14 False

expandtabs()

把字符串中的 tab 符号('\t')转为空格,

tab 符号('\t')默认的空格数是 8

s.expandtabs(tabsize=8)
tabsize -- 指定转换字符串中的 tab 符号('\t')转为空格的字符数。
1 >>>str = "this is\tstring example....wow!!!"
2
3 >>>print("Original string: " + str)
4 >>>print("Defualt exapanded tab: " + str.expandtabs())
5 >>>print("Double exapanded tab: " + str.expandtabs(16))
6
7 Original string: this is string example....wow!!!
8 Defualt exapanded tab: this is string example....wow!!!
9 Double exapanded tab: this is string example....wow!!!
find()

检测字符串中是否包含子字符串 str

可指定范围,若含子字符串返回索引值,否则返回-1

s.find(str, beg=0, end=len(string))
str -- 指定检索的字符串

beg -- 开始索引,默认为0。

end -- 结束索引,默认为字符串的长度。

 1 >>>str1 = "this is string example....wow!!!"
2 >>>str2 = "exam"
3
4 >>>print(str1.find(str2))
5 >>>print(str1.find(str2, 10))
6 >>>print(str1.find(str2, 40))
7
8 15
9 15
10 -1
11
12
13 >>>info = 'abca'
14 >>>print(info.find('a')) # 从下标0开始,查找在字符串里第一个出现的子串,返回结果:0
15 0
16 >>> print(info.find('a',1)) # 从下标1开始,查找在字符串里第一个出现的子串:返回结果3
17 3
18 >>> print(info.find('3')) # 查找不到返回-1
19 -1

format()

通过 {} 和 : 来代替以前的 %

format 函数可以接受不限个参数,位置可以不按顺序

s.format(*args, **kwargs)
 

1 >>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
2 'hello world'
3
4 >>> "{0} {1}".format("hello", "world") # 设置指定位置
5 'hello world'
6
7 >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
8 'world hello world'
 1 print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
2
3 # 通过字典设置参数
4 site = {"name": "菜鸟教程", "url": "www.runoob.com"}
5 print("网站名:{name}, 地址 {url}".format(**site))
6
7 # 通过列表索引设置参数
8 my_list = ['菜鸟教程', 'www.runoob.com']
9 print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的
10
11
12 网站名:菜鸟教程, 地址 www.runoob.com
13 网站名:菜鸟教程, 地址 www.runoob.com
14 网站名:菜鸟教程, 地址 www.runoob.com
 1 #str.format() 格式化数字
2 >>> print("{:.2f}".format(3.1415926));
3
4 3.14
5
6 #{:.2f} -> 保留小数点后两位
7 #{:+.2f} -> 带符号保留小数点后两位
8 #{:.0f} -> 不带小数
9 #{:0>2d} -> 数字补零 (填充左边, 宽度为2)
10 #{:x<4d} -> 数字补x (填充右边, 宽度为4)
11 #{:,} -> 以逗号分隔的数字格式
12 #{:.2%} -> 百分比格式
13 #{:.2e} -> 指数记法
14 #{:>10d} -> 右对齐 (默认, 宽度为10)
15 #{:<10d} -> 左对齐 (宽度为10)
16 #{:^10d} -> 中间对齐 (宽度为10)
17
18 '{:b}'.format(11) -> 1011
19 '{:d}'.format(11) -> 11
20 '{:o}'.format(11) -> 13
21 '{:x}'.format(11) -> b
22 '{:#x}'.format(11) -> 0xb
23 '{:#X}'.format(11) -> 0xB
24
25 #总结:
26 '''
27 ^, <, > 分别是居中、左对齐、右对齐,后面带宽度,
28 : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
29 + 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格
30 b、d、o、x 分别是二进制、十进制、八进制、十六进制。
31 '''
1 #使用大括号 {} 来转义大括号
2
3 >>>print ("{} 对应的位置是 {{0}}".format("runoob"))
4
5 runoob 对应的位置是 {0}
index()

检测字符串中是否包含子字符串 str

可指定范围,类似find(),如果不在就报错

s.index(str, beg=0, end=len(string))
str -- 指定检索的字符串

beg -- 开始索引,默认为0。

end -- 结束索引,默认为字符串的长度。

 1 >>>str1 = "this is string example....wow!!!"
2 >>>str2 = "exam"
3
4 >>>print(str1.index(str2))
5 >>>print(str1.index(str2, 10))
6 >>>print(str1.index(str2, 40))
7
8 15
9
10 Traceback (most recent call last):
11 File "test.py", line 8, in
12 print str1.index(str2, 40);
13 ValueError: substring not found
14
15 15
isalnum() 检测字符串是否由字母和数字组成
s.isalnum()
1 >>>str = "this2009" # 字符中没有空格
2 >>>print(str.isalnum())
3
4 >>>str = "this is string example....wow!!!"
5 >>>print(str.isalnum())
6
7 True
8 False
isalpha()  检测字符串是否只由字母组成
s.isalpha()
 1 str = "runoob"
2 print(str.isalpha())
3
4 str = "runoob菜鸟教程"
5 print(str.isalpha())
6
7 str = "this is string example....wow!!!"
8 print(str.isalpha())
9
10
11
12 True
13 False
14 False
isdigit() 检测字符串是否只由数字组成
s.isdigit()
1 >>>str = "123456"  # Only digit in this string
2 >>>print(str.isdigit())
3
4 >>>str = "this is string example....wow!!!"
5 >>>print(str.isdigit())
6
7 True
8 False
isdecimal()
检查字符串是否只包含十进制字符
存在于unicode对象
定义一个十进制字符串,只需要在字符串前添加 'u' 前缀即可

s.isdecimal()

 无
str = "runoob2016"
print (str.isdecimal()) str = "23443434"
print (str.isdecimal()) '''
False
True '''
islower()
检测字符串是否由小写字母组成
s.islower()
1 >>>str = "THIS is string example....wow!!!"
2 >>>print(str.islower())
3
4 >>>str = "this is string example....wow!!!"
5 >>>print(str.islower())
6
7 False
8 True
isnumeric()

检测字符串是否只由数字组成

只针对unicode对象

定义一个字符串为Unicode,只需要在字符串前添加 'u' 前缀即可

s.isnumeric()
 
1 >>>str = u"this2009"
2 >>>print(str.isnumeric())
3
4 >>>str = u"23443434"
5 >>>print(str.isnumeric())
6
7
8 False
9 True

isspace()

 检测字符串是否只由空格组成

s.isspace()
 无
1 >>>str = "       "
2 >>>print(str.isspace())
3
4 >>>str = "This is string example....wow!!!"
5 >>>print(str.isspace())
6
7
8 True
9 False

istitle()

检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写

s.istitle()
 无
 1 >>>str = "This Is String Example...Wow!!!"
2 >>>print(str.istitle())
3
4 >>>str = "This is string example....wow!!!"
5 >>>print(str.istitle())
6
7
8
9 True
10 False
isupper() 检测字符串中所有的字母是否都为大写
s.isupper() 
1 >>>str = "THIS IS STRING EXAMPLE....WOW!!!";
2 >>>print(str.isupper())
3
4 >>>str = "THIS is string example....wow!!!"
5 >>>print(str.isupper())
6
7 True
8 False
join() 将序列中的元素以指定的字符连接生成一个新的字符串
s.join(sequence)
sequence -- 要连接的元素序列
1 >>>str = "-"
2 >>>seq =str.join("abc")
3
4 >>>print(seq)
5
6 a_b_c
len() 返回对象(字符、列表、元组等)长度或项目个数
len( s )
s -- 对象
1 >>>str = "runoob"
2 >>> len(str) # 字符串长度
3 6
4 >>> l = [1,2,3,4,5]
5 >>> len(l) # 列表元素个数
6 5
ljust()

返回一个原字符串左对齐,默认使用空格填充至长度 width 的新字符串

如果指定的长度小于原字符串的长度则返回原字符串。

s.ljust(width[, fillchar])

width -- 指定字符串长度。

fillchar -- 填充字符,默认为空格。

1 >>>str = "this is string example....wow!!!"
2
3 >>>print(str.ljust(50, '0'))
4
5
6 this is string example....wow!!!000000000000000000
lower() 转换字符串中所有大写字符为小写
s.lower()
1 >>>str = "THIS IS STRING EXAMPLE....WOW!!!"
2
3 >>>print(str.lower())
4
5 this is string example....wow!!!
lstrip() 截掉字符串左边的空格或指定字符
s.lstrip([chars])
chars --指定截取的字符
1 >>>str = "     this is string example....wow!!!     "
2 >>>print(str.lstrip())
3
4 >>>str = "88888888this is string example....wow!!!8888888"
5 >>>print(str.lstrip('8')0
6
7
8 this is string example....wow!!!
9 this is string example....wow!!!8888888
maketrans()

创建字符映射的转换表

两个字符串的长度必须相同,一一对应

s.maketrans(intab, outtab)

intab -- 字符串中要替代的字符组成的字符串

outtab -- 相应的映射字符的字符串

1 >>>intab = "aeiou"
2 >>>outtab = "12345"
3 >>>trantab = maketrans(intab, outtab)
4
5 >>>str = "this is string example....wow!!!"
6 >>>print(str.translate(trantab))
7
8
9 th3s 3s str3ng 2x1mpl2....w4w!!!
max() 返回字符串中最大的字母
max(str)
str -- 字符串
1 >>>str = "this is really a string example....wow!!!"
2 >>>print("Max character: " + max(str))
3
4 >>>str = "this is a string example....wow!!!"
5 >>>print("Max character: " + max(str))
6
7
8 Max character: y
9 Max character: x
min()  返回字符串中最小的字母
min(str)
str -- 字符串
1 >>>str = "this-is-real-string-example....wow!!!"
2 >>>print("Min character: " + min(str))
3
4 >>>str = "this-is-a-string-example....wow!!!"
5 >>>print("Min character: " + min(str))
6
7 Min character: !
8 Min character: !
partition()

根据指定的分隔符将字符串进行分割

如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串

s.partition(str)
str -- 指定的分隔符
1 >>>str = "www.runoob.com"
2
3 >>>print(str.partition("."))
4
5 ('www', '.', 'runoob.com')
replace()

把旧字符串替换成新字符串

可指定替换次数

s.replace(old, new[, max]) 

old -- 将被替换的子字符串。

new -- 新字符串,用于替换old子字符串。

max -- 可选字符串, 替换不超过 max 次

1 >>>str = "this is string example....wow!!! this is really string"
2
3 >>>print(str.replace("is", "was"))
4 >>>print(str.replace("is", "was", 3))
5
6 thwas was string example....wow!!! thwas was really string
7 thwas was string example....wow!!! thwas is really string
rfind() 

返回字符串最后一次出现的位置(从右向左查询),

如果没有匹配项则返回-1

s.rfind(str, beg=0 end=len(string))

str -- 查找的字符串

beg -- 开始查找的位置,默认为 0

end -- 结束查找位置,默认为字符串的长度。

 1 >>>str = "this is really a string example....wow!!!"
2 >>>substr = "is"
3
4 >>>print(str.rfind(substr))
5 >>>print(str.rfind(substr, 0, 10))
6 >>>print(str.rfind(substr, 10, 0))
7
8 >>>print(str.find(substr))
9 >>>print(str.find(substr, 0, 10))
10 >>>print(str.find(substr, 10, 0))
11
12
13 5
14 5
15 -1
16 2
17 2
18 -1
rindex()

返回子字符串 str 在字符串中最后出现的位置

可指定范围,如果没有匹配的字符串会报异常

s.rindex(str, beg=0 end=len(string))

str -- 查找的字符串

beg -- 开始查找的位置,默认为0

end -- 结束查找位置,默认为字符串的长度。

1 >>>str1 = "this is string example....wow!!!"
2 >>>str2 = "is"
3
4 >>>print(str1.rindex(str2))
5 >>>print(str1.index(str2))
6
7 5
8 2
rjust()

返回一个原字符串右对齐,默认使用空格填充至长度 width 的新字符串

如果指定的长度小于字符串的长度则返回原字符串。

s.rjust(width[, fillchar])

width -- 指定填充指定字符后中字符串的总长度.

fillchar -- 填充的字符,默认为空格。

1 >>>str = "this is string example....wow!!!"
2
3 >>>print(str.rjust(50, '0'))
4
5 000000000000000000this is string example....wow!!!
rstrip()  截掉字符串右边的空格或指定字符
s.rstrip([chars])
chars -- 指定删除的字符(默认为空格)
1 >>>str = "     this is string example....wow!!!     "
2 >>>print(str.rstrip())
3
4 >>>str = "88888888this is string example....wow!!!8888888"
5 >>>print(str.rstrip('8'))
6
7
8 this is string example....wow!!!
9 88888888this is string example....wow!!!
split() 

通过指定分隔符对字符串进行切片

如果参数 num 有指定值,则分隔num处

s.split(str="", num=string.count(str))

str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。

num -- 分割次数。默认为 -1, 即分隔所有。

1 >>>str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
2
3 >>>print(str.split( )) # 以空格为分隔符,包含 \n
4 >>>print(str.split(' ', 1 )) # 以空格为分隔符,分隔成两个
5
6
7 ['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
8 ['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
splitlines()

按照行('\r', '\r\n', \n')分隔

默认不保留换行符,若参数为 True,则保留

s.splitlines([keepends]) 
keepends -- 明确输出结果内是否保留换行符,默认为 False,不保留,若为 True,则保留。
1 >>>str1 = 'ab c\n\nde fg\rkl\r\n'
2 >>>print(str1.splitlines())
3
4 >>>str2 = 'ab c\n\nde fg\rkl\r\n'
5 >>>print(str2.splitlines(True))
6
7 ['ab c', '', 'de fg', 'kl']
8 ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
startswith()

检查字符串是否是以指定子字符串开头

可指定范围

s.startswith(str, beg=0,end=len(string)) 

str -- 检测的字符串。

strbeg -- 可设置字符串检测的起始位置。

strend -- 可设置字符串检测的结束位置。

1 >>>str = "this is string example....wow!!!"
2
3 >>>print(str.startswith( 'this' ))
4 >>>print(str.startswith( 'is', 2, 4 ))
5 >>>print(str.startswith( 'this', 2, 4 ))
6
7 True
8 True
9 False
strip()

移除字符串头尾指定的字符

默认为空格或换行符,可设置为字符序列

s.strip([chars]) 

chars -- 移除字符串头尾指定的字符序列

 1 >>>str = "00000003210Runoob01230000000"
2 >>>print(str.strip( '0' )) # 去除首尾字符 0
3
4
5 >>>str2 = " Runoob " # 去除首尾空格
6 >>>print(str2.strip())
7
8 >>>str = "123abcrunoob321"
9 >>>print (str.strip( '12' )) # 字符序列为 12
10
11
12 3210Runoob0123
13 Runoob
14 3abcrunoob3
swapcase() 对字符串的大小写字母进行转换
s.swapcase()
1 >>>str = "this is string example....wow!!!"
2 >>>print(str.swapcase())
3
4 >>>str = "THIS IS STRING EXAMPLE....WOW!!!"
5 >>>print(str.swapcase())
6
7 THIS IS STRING EXAMPLE....WOW!!!
8 this is string example....wow!!!
title() 所有单词都是以大写开始,其余字母均为小写
s.title()
1 >>>str = "this is string example....wow!!!"
2
3 >>>print(str.title())
4
5
6 This Is String Example....Wow!!!
translate()

根据给出的表转换字符

要过滤掉的字符放到 del 参数中

s.translate(table[, deletechars]) 

table -- 翻译表,通过maketrans转换而deletechars -- 字符串中要过滤的字符列表

1 >>>intab = "aeiou"
2 >>>outtab = "12345"
3 >>>trantab = maketrans(intab, outtab)
4
5 >>>str = "this is string example....wow!!!"
6 >>>print(str.translate(trantab))
7
8
9 th3s 3s str3ng 2x1mpl2....w4w!!!
upper() 将字符串中的小写字母转为大写字母
s.upper()
1 >>>str = "this is string example....wow!!!"
2
3 >>>print(str.upper())
4
5 THIS IS STRING EXAMPLE....WOW!!!

格式化输入

百分号拼接字符串

print ("我叫 %s 今年 %d 岁!" % ('小明', 10))

'''
我叫 小明 今年 10 岁! '''
'''
%c 格式化字符及其ASCII码
%s 格式化字符串
%d 格式化整数
%u 格式化无符号整型
%o 格式化无符号八进制数
%x 格式化无符号十六进制数
%X 格式化无符号十六进制数(大写)
%f 格式化浮点数字,可指定小数点后的精度
%e 用科学计数法格式化浮点数
%E 作用同%e,用科学计数法格式化浮点数
%g %f和%e的简写
%G %f 和 %E 的简写
%p 用十六进制数格式化变量的地址 '''

python字符串格式化符号

format字符串格式化

python三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符

para_str = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( \t )。
也可以使用换行符 [ \n ]。
""" print (para_str) '''
这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( )。
也可以使用换行符 [
]。 '''

三、列表(list)

列表是Python内置的一种数据类型是列表,是一种有序的集合,可以随时添加和删除其中的元素。

列表方法

方法名 描述 语法 参数            
cmp()

比较两个列表的元素

如果比较的元素是同类型的,则比较其值,返回结果

如果两个元素不是同一种类型,则检查它们是否是数字

两方全是数字则转换成int值比较,一方是数字则它小

否则,通过类型名字的字母顺序进行比较

cmp(list1, list2)

st1 -- 比较的列表。

list2 -- 比较的列表

>>>list1, list2 = [123, 'xyz'], [456, 'abc']

>>>print(cmp(list1, list2))
>>>print(cmp(list2, list1))
>>>list3 = list2 + [786]
>>>print(cmp(list2, list3)) '''
-1
1
-1 '''
len()  返回列表元素个数
len(list)
list -- 要计算元素个数的列表
>>>list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']

>>>print("First list length : ", len(list1))
>>>print("Second list length : ", len(list2)) '''
First list length : 3
Second lsit length : 2 '''
max() 返回列表元素中的最大值
max(list)
list -- 要返回最大值的列表
>>>list1, list2 = ['123', 'xyz', 'zara', 'abc'], [456, 700, 200]

>>>print("Max value element : ", max(list1))
>>>print("Max value element : ", max(list2)) '''
Max value element : zara
Max value element : 700 '''
min() 返回列表元素中的最小值
min(list)
list -- 要返回最小值的列表
>>>list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]

>>>print("min value element : ", min(list1))
>>>print("min value element : ", min(list2)) '''
min value element : 123
min value element : 200 '''
list() 将元组或字符串转换为列表
list( tup )
tup -- 要转换为列表的元组
aTuple = (123, 'xyz', 'zara', 'abc')
aList = list(aTuple) print("列表元素 : ", aList) '''
列表元素 : [123, 'xyz', 'zara', 'abc'] '''
append() 在列表末尾添加新的对象
list.append(obj)
obj -- 添加到列表末尾的对象
>>>aList = [123, 'xyz', 'zara', 'abc']
>>>aList.append( 2009 ) >>>print("Updated List : ", aList) '''
Updated List : [123, 'xyz', 'zara', 'abc', 2009] '''
count()  统计某个元素在列表中出现的次数  list.count(obj)  obj -- 列表中统计的对象

>>>aList = [123, 'xyz', 'zara', 'abc', 123]

>>>print("Count for 123 : ", aList.count(123))
>>>print("Count for zara : ", aList.count('zara')) '''
Count for 123 : 2
Count for zara : 1 '''
extend()

在列表末尾一次性追加另一个序列中的多个值

用新列表扩展原来的列表

 list.extend(seq)  seq -- 元素列表
aList = [123, 'xyz', 'zara', 'abc', 123]
bList = [2009, 'manni']
aList.extend(bList) print("Extended List : ", aList) '''
Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni'] '''
index() 从列表中找出与某个值第一个匹配项的索引位置  list.index(x[, start[, end]])  x-- 查找的对象

start-- 可选,起始位置

end-- 可选,结束位置

>>>aList = [123, 'xyz', 'runoob', 'abc']

>>>print("xyz 索引位置: ", aList.index( 'xyz' ))
>>>print("runoob 索引位置 : ", aList.index( 'runoob', 1, 3 )) '''
xyz 索引位置: 1
runoob 索引位置 : 2 '''
insert()  将指定对象插入列表的指定位置  list.insert(index, obj)

index -- 需要插入的位置

obj -- 要插入的对象

>>>aList = [123, 'xyz', 'zara', 'abc']
>>>aList.insert( 3, 2009) >>>print("Final List : ", aList) '''
Final List : [123, 'xyz', 'zara', 2009, 'abc'] '''
pop()

用于移除列表中的一个元素,并且返回该元素的值

默认最后一个元素

 list.pop([index]) index -- 要移除的元素的索引值
>>>list1 = ['Google', 'Runoob', 'Taobao']
>>>list_pop=list1.pop(1) >>>print("删除的项为 :", list_pop)
>>>print("列表现在为 : ", list1) '''
删除的项为 : Runoob
列表现在为 : ['Google', 'Taobao'] '''
remove()  移除列表中某个值的第一个匹配项  list.remove(obj)  obj -- 列表中要移除的对象
>>>aList = [123, 'xyz', 'zara', 'abc', 'xyz']
>>>aList.remove('xyz') >>>print("List : ", aList) >>>aList.remove('abc') >>>print("List : ", aList) '''
List : [123, 'zara', 'abc', 'xyz']
List : [123, 'zara', 'xyz'] '''
reverse()  反转列表中元素  list.reverse()
>>>aList = [123, 'xyz', 'zara', 'abc', 'xyz']
>>>aList.reverse() >>>print("List : ", aList) '''
List : ['xyz', 'abc', 'zara', 'xyz', 123] '''
sort()

对原列表进行排序

默认降序,可指定排序方法

list.sort(cmp=None, key=None, reverse=False)

cmp --指定排序方法

key -- 指定可迭代对象中的一个元素来进行排序

reverse -- 排序规则reverse = True 降序reverse = False 升序(默认)

>>>aList = [123, 'Google', 'Runoob', 'Taobao', 'Facebook']
>>>aList.sort() >>>print("List : ", aList) '''
List : [123, 'Facebook', 'Google', 'Runoob', 'Taobao'] '''

四、元组(tuple)

tuple和list非常类似,但是tuple一旦初始化就不能修改,tuple也是有序的,tuple使用的是小括号标识。

元组方法

方法名 描述 语法 参数
cmp()

用于比较两个元组元素

类似列表

cmp(tuple1, tuple2)

tuple1 -- 比较的元组

tuple2 -- 比较的另外一个元组

>>>tuple1, tuple2 = (123, 'xyz'), (456, 'abc')

>>>print(cmp(tuple1, tuple2))
>>>print(cmp(tuple2, tuple1)) >>>tuple3 = tuple2 + (786,) >>>print(cmp(tuple2, tuple3)) >>>tuple4 = (123, 'xyz') >>>print(cmp(tuple1, tuple4)) '''
-1
1
-1
0 '''
tuple() 将列表或字符串转换为元组
tuple( iterable )
iterable -- 要转换为元组的可迭代序列
(1, 2, 3, 4)

>>> tuple({1:2,3:4})    #针对字典 会返回字典的key组成的tuple

(1, 3)

>>> tuple((1,2,3,4))    #元组会返回元组自身

(1, 2, 3, 4)
>>>aList = [123, 'xyz', 'zara', 'abc']
>>>aTuple = tuple(aList) >>>print("Tuple elements : ", aTuple) '''
Tuple elements : (123, 'xyz', 'zara', 'abc') '''

五、字典(dict)

字典是另一种可变容器模型,且可存储任意类型对象,如其他容器模型。

字典由键和对应值成对组成。字典也被称作关联数组或哈希表。

键必须独一无二,但值则不必,可以取任何数据类型

但键必须是不可变的,可以是字符串,数字,元组,布尔值

字典方法

方法名 描述                             语法 参数      
clear() 删除字典内所有元素
dict.clear()
>>>dict = {'Name': 'Zara', 'Age': 7}

>>>print("Start Len : " , len(dict))

>>>dict.clear()

>>>print("End Len : " , len(dict))

'''
Start Len : 2
End Len : 0 '''
copy() 返回一个字典的浅复制
dict.copy()
>>>dict1 = {'Name': 'Zara', 'Age': 7};
>>>dict2 = dict1.copy() >>>print("New Dictinary : " , str(dict2)) '''
New Dictinary : {,'Name': 'Zara' , 'Age': 7} '''
>>>dict1 =  {'user':'runoob','num':[1,2,3]}

>>>dict2 = dict1             # 浅拷贝: 引用对象
>>>dict3 = dict1.copy() # 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用 # 修改 data 数据
>>>dict1['user']='root'
>>>dict1['num'].remove(1) # 输出结果
>>>print(dict1)
>>>print(dict2)
>>>print(dict3) '''
{'user': 'root' , 'num': [2, 3]}
{'user': 'root' , 'num': [2, 3]}
{'user': 'runoob' , 'num': [2, 3],} '''
fromkeys()

创建一个新字典

以序列 seq 中元素做字典的键

value 为字典所有键对应的初始值

dict.fromkeys(seq[, value]) 

seq -- 字典键值列表

value -- 可选,设置键序列的值。

>>>seq = ('Google', 'Runoob', 'Taobao')
>>>dict = dict.fromkeys(seq) >>>print("新字典为 :",str(dict)) >>>dict = dict.fromkeys(seq, 10) >>>print("新字典为 :",str(dict)) '''
新字典为 : {'Google': None, 'Taobao': None, 'Runoob': None}
新字典为 : {'Google': 10, 'Taobao': 10, 'Runoob': 10} '''
get()

返回指定键的值

如果值不在字典中返回设定值,默认为None

dict.get(key, default=None)

key -- 要查找的键。

default -- 若指定键不存在,返回该值

>>>dict = {'Name': 'Zara', 'Age': 27}

>>>print("Value : ",dict.get('Age'))
>>>print("Value : ",dict.get('Sex', "Never")) '''
Value : 27
Value : Never '''
has_key() 判断键是否存在于字典中
dict.has_key(key)
key -- 要查找的键
>>>dict = {'Name': 'Zara', 'Age': 7}

>>>print("Value : " , dict.has_key('Age'))
>>>print("Value : " , dict.has_key('Sex')) '''
Value : True
Value : False '''
items()  以列表返回所有的键值对
dict.items()
>>>dict = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com', 'taobao': 'www.taobao.com'}

>>>print("字典值 : " , dict.items())

# 遍历字典列表
>>>for key,values in dict.items():
>>> print(key,values) '''
字典值 : [('Google', 'www.google.com'), ('taobao', 'www.taobao.com'), ('Runoob', 'www.runoob.com')]
Google www.google.com
taobao www.taobao.com
Runoob www.runoob.com '''
keys() 以列表返回所有的键
dict.keys()
>>>dict = {'Name': 'Zara', 'Age': 7}

>>>print("Value :" , dict.keys())

'''
Value : ['Age', 'Name'] '''
setdefault()

添加键值对

若键已存在,仅返回对应的值

若键未存在,创建键值对并返回设置后的值,默认为None

dict.setdefault(key, default=None)

key -- 查找的键

default -- 键不存在时,设置的值

>>>dict = {'runoob': '菜鸟教程', 'google': 'Google 搜索'}

>>>print(“Value : " , dict.setdefault('runoob', None))
>>>print("Value : " , dict.setdefault('Taobao', '淘宝')) '''
Value : 菜鸟教程
Value : 淘宝 '''
update()

把字典dict2的键/值对更新到dict

还有一种 =表达式  -> k1 = 'abc'

有相同的键会直接替换成 update 的值

dict.update(dict2)
dict2 -- 添加到指定字典dict里的字典
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>dict2 = {'Sex': 'female' }
>>>dict.update(dict2) >>>print("Value : " , dict) '''
Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}
'''
values() 以列表返回字典中的所有值
dict.values()
>>>dict = {'Name': 'Zara', 'Age': 7}

>>>print("Value : " , dict.values())

'''
Value : [7, 'Zara'] '''
 pop()

删除给定键及对应的值

返回值为被删除的值

key 值必须给出,否则返回 default 值

pop(key[,default])

key: 要删除的键值

default: 如果没有 key,返回 default 值

>>>site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'}
>>>pop_obj=site.pop('name') >>>print(pop_obj) '''
菜鸟教程 '''
 popitem()

随机删除字典中的一个键值对

(key,value)的形式返回该键值对

popitem()
>>>d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>>pop_obj = d.popitem() >>>print('pop_obj:', pop_obj)
>>>print('dict:', d) '''
pop_obj: ('c', 3)
dict: {'b': 2, 'd': 4, 'a': 1} '''

六、集合(set)

集合(set)由不同元素组成(自动去重),无序排列(不可索引),元素为可hash值(不可变类型:数字、字符串、元组)

可以使用大括号 { } 或者 set() 函数创建集合

注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

运算 符号
交集  &
并集  |
交叉补集  ^
差集  -

集合方法

方法名 描述 语法 参数
add()

给集合添加元素

如果添加的元素在集合中已存在,则不执行任何操作

set.add(elmnt)
elmnt -- 必需,要添加的元素
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits) '''
{'apple', 'banana', 'orange', 'cherry'} '''
clear() 移除集合中的所有元素
set.clear()
fruits = {"apple", "banana", "cherry"}
fruits.clear()
print(fruits) '''
set() '''
copy() 拷贝一个集合
set.copy()
fruits = {"apple", "banana", "cherry"}
x = fruits.copy()
print(x) '''
{'cherry', 'banana', 'apple'} '''
difference()

返回集合的差集

即返回的集合元素包含在第一个集合中,但不包含在第二个集合(参数)中

set.difference(set)
set -- 必需,用于计算差集的集合
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"} z = x.difference(y) print(z) '''
{'cherry', 'banana'} '''
difference_update()

移除两个集合中都存在的元素

set.difference_update(set)
set -- 必需,用于计算差集的集合
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"} x.difference_update(y) print(x) '''
{'cherry', 'banana'} '''
discard()

移除指定的集合元素

元素不存在时不报错

set.discard(value)
value -- 必需,要移除的元素
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana") print(fruits) '''
{'cherry', 'apple'} '''
intersection()

返回两个或更多集合中都包含的元素,即交集

set.intersection(set1, set2 ... etc)

set1 -- 必需,要查找相同元素的集合

set2 -- 可选,其他要查找相同元素的集合,可以多个,多个使用逗号 , 隔开

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"} z = x.intersection(y) print(z) '''
{'apple'} '''
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"} result = x.intersection(y, z) print(result) '''
{'c'} '''
 intersection_update()

获取两个或更多集合中都重叠的元素,即交集

在原始的集合上移除不重叠的元素

set.intersection_update(set1, set2 ... etc)
 set1 -- 必需,要查找相同元素的集合

set2 -- 可选,其他要查找相同元素的集合,可以多个,多个使用逗号 , 隔开

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"} x.intersection_update(y) print(x) '''
{'apple'} '''
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"} x.intersection_update(y, z) print(x) '''
{'c'} '''
 isdisjoint()  判断两个集合是否包含相同的元素

set.isdisjoint(set)

 set -- 必需,要比较的集合
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "facebook"} z = x.isdisjoint(y) print(z) '''
True '''
 issubset()

判断前者是否为子集

 set.issubset(set)  set -- 必需,要比查找的集合
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"} z = x.issubset(y) print(z) '''
True '''
 issuperset()  判断前者是否为父集

set.issuperset(set)

 set -- 必需,要比查找的集合
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"} z = x.issuperset(y) print(z) '''
True '''
 pop()

随机移除一个元素

因为集合是无序的

set.pop()
 无
fruits = {"apple", "banana", "cherry"}

fruits.pop() 

print(fruits)

'''
{'apple', 'banana'} '''
 remove()

移除集合中的指定元素

元素不存在时会报错

set.remove(item)
 item -- 要移除的元素
fruits = {"apple", "banana", "cherry"}

fruits.remove("banana") 

print(fruits)

'''
{'cherry', 'apple'} '''
 symmetric_difference()  返回两个集合中不重复的元素集合,即会移   除两个集合中都存在的元素

set.symmetric_difference(set)

 set -- 集合
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"} z = x.symmetric_difference(y) print(z) '''
{'google', 'cherry', 'banana', 'runoob'} '''
 symmetric_difference_update() 

移除当前集合中在另外一个指定集合相   同的元素

并将另外一个指定集合中不同的元素插     入到当前集合中

set.symmetric_difference_update(set)
 set -- 要检测的集合
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"} x.symmetric_difference_update(y) print(x) '''
{'google', 'cherry', 'banana', 'runoob'} '''
 union()

返回两个集合的并集,

即包含了所有集合的元素,重复的元素   只会出现一次

set.union(set1, set2...)

set1 -- 必需,合并的目标集合

set2 -- 可选,其他要合并的集合,可以多个,多个使用逗号 , 隔开

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"} z = x.union(y) print(z) '''
{'cherry', 'runoob', 'google', 'banana', 'apple'} '''
x = {"a", "b", "c"}
y = {"f", "d", "a"}
z = {"c", "d", "e"} result = x.union(y, z) print(result) '''
{'c', 'd', 'f', 'e', 'b', 'a'} '''
 update()

修改当前集合

可以添加新的元素或集合到当前集合        中,重复的元素会忽略。

set.update(set)
 set -- 必需,可以是元素或集合
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"} x.update(y) print(x) '''
{'banana', 'apple', 'google', 'runoob', 'cherry'} '''

02----python入门----基本数据类型的更多相关文章

  1. Python 入门之数据类型之间的相互转换 以及 在编程中会遇到的数据类型的坑

    Python 入门之数据类型之间的相互转换 以及 在编程中会遇到的数据类型的坑 1.数据类型总结: 可变,不可变,有序,无序 (1)可变的数据类型:list dict set (2)不可变的数据类型: ...

  2. python入门day02数据类型

    字符串:数据类型的学习 #======================================基本使用====================================== #1.用途 ...

  3. python入门之数据类型及内置方法

    目录 一.题记 二.整形int 2.1 用途 2.2 定义方式 2.3 常用方法 2.3.1 进制之间的转换 2.3.2 数据类型转换 3 类型总结 三.浮点型float 3.1 用途 3.2 定义方 ...

  4. python入门之数据类型之列表、元组、字典

    list 格式: test_list = ["a",123,[1,"b"]] 索引: >>>print(test_list[0]) " ...

  5. python入门之数据类型之字符串

    str方法 name.capitalize() 将name的首字母大写 name.center(20,'*') 将name居中,长度变为20,其余用*填充 name.count('chy') 返回na ...

  6. 02 . Python之数据类型

    Python入门之数据类型 变量存储在内存中的值.这就意味着在创建变量时会在内存中开辟一个空间.基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中. 因此,变量可以指定不同的数 ...

  7. Python入门篇-基础数据类型之整型(int),字符串(str),字节(bytes),列表(list)和切片(slice)

    Python入门篇-基础数据类型之整型(int),字符串(str),字节(bytes),列表(list)和切片(slice) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Py ...

  8. python入门(8)数据类型和变量

    python入门(8)数据类型和变量 数据类型 在Python中,能够直接处理的数据类型有以下几种: 整数 Python可以处理任意大小的整数,当然包括负整数,在程序中的表示方法和数学上的写法一模一样 ...

  9. Python入门学习:1.变量和简单的数据类型

    python入门学习:1.变量和简单的数据类型 关键点:变量.字符串.数字 1.1 变量的命名和使用1.2 字符串1.3 数字1.4 注释 1.1 变量的命名和使用   变量,顾名思义是一个可变的量, ...

  10. Python 入门之基本数据类型

    为什么我要学习Python这门语言呢?其实很简单,我想拓展技术面的同时,尝试更多的方向,可能最后会不了了之,谁知道呢?有可能的话,我会向爬虫和数据分析这个方向走.所以也就开始了我的Python学习之旅 ...

随机推荐

  1. POJ1142 Smith Numbers 暴力+分解质因子

    题意:题目定义了一个史密斯数,这个数的定义是:一个合数的各个位置上加起来的和等于它的素因数所有位置上的数字加起来的和.比如: 4937775=3∗5∗5∗658374+9+3+7+7+7+5=3+5+ ...

  2. http post请求数组参数写法

    1.json形式 body如下(注意是中括号): [ *, *, * ] postman: fiddler: 2.x-www-form-urlencoded postman: fiddler: 3.服 ...

  3. AWS注册到连接

    1. 注册AWS账号 https://www.cnblogs.com/cmt/p/13912814.html 2.注册完成之后,选择实例 Ubuntu,下载xxx.pem文件,查看实例得到ip 比如我 ...

  4. SpringBoot整合shiro-MD5盐值加密

    为什么要进行密码加密? 在我们的日常生活中,许多人有着在不同网站上使用相同密码的坏习惯(包括我也是qaq),假如应用程序或服务器出现漏洞,数据被窃取,用户的明文密码直接被暴露给黑客.显然后果将不堪设想 ...

  5. Base64 编码原理

    什么是 Base64 编码 Base64 编码是最常见的编码方式,基于 64 个可打印字符来表示任意二进制数据的方法,是从二进制转换到可见字符的过程. 使用场景 数据加密或签名通过 Base64 转换 ...

  6. MBP 屏幕分辨率 All In One

    MBP 屏幕分辨率 All In One screen size bug https://stackoverflow.com/questions/65462643/how-to-get-the-rea ...

  7. web 前端工具: Gulp 使用教程

    1 1 1 Gulp 使用教程: 1 1 1 1 1 1 1 1 ERROR: ./app.js 当前目录路径: ./ 当前目录路径: ./ 1 1 1 1 1 参考资源: http://webpac ...

  8. LeetCode 最大收益的分配工作

    LeetCode 最大收益的分配工作 工作安排 现在有n位工程师和6项工作(编号为0至5),现在给出每个人能够胜任的工作序号表(用一个字符串表示,比如:045,表示某位工程师能够胜任0号,4号,5号工 ...

  9. Xcode 格式化 SwiftUI代码

    Xcode 格式化 SwiftUI 代码 代码缩进 代码缩进 格式化 快捷键 Control + i ⌃ + i how to input mac keyboard symbol key ⌃ cont ...

  10. leetcode bug & 9. Palindrome Number

    leetcode bug & 9. Palindrome Number bug shit bug "use strict"; /** * * @author xgqfrms ...