基础数据类型(不可变数据类型)
可变数据类型和不可变数据类型的定义
不可变数据类型:
即不可以在源数据的基础上发生改变,如果想要通过某些运算或者方法来改变源数据,则会重新开辟空间存储结果,并不会影响源数据
1 a = 3 2 print(id(a + 3)) 3 print(id(a)) 4 5 6 """ 7 1623616688 8 1623616592 9 """
可变数据类型 :
即可以在源数据的基础上发生改变,内存地址不会发生改变
1 a = [1,2,3] 2 print(id(a)) 3 a += [2,3,4] 4 print(id(a)) 5 6 """ 7 2243534804936 8 2243534804936 9 """
1 a = [1,2,3] 2 print(id(a)) 3 a = a + [2,3,4] 4 print(id(a)) 5 6 """ 7 2875843041224 8 2875843041096 9 列表在做+运算的时候,不管是可变数据类型还是不可变数据类型都会重新开辟空间存放结果, 10 """ 11 12 a = [1,2,3] 13 print(id(a)) 14 a += [2,3,4] 15 print(id(a)) 16 17 """ 18 1827113031624 19 1827113031624 20 +=运算会判断其数据类型是否可变,如果可变则在原基础上运算,如果不可变则会重新开辟空间 21 """
数字,用以计算比较
#python2 中没有int类型
long(长整型) / 获取的是整数 -->int类型
#python3 中 整型int --> 整数
32位/64位 范围
1. 整型的32位 -2 ** 31 ~ 2 **31-1
2. 整型的64位 -2** 63 ~ 2 **63-1
十二进制转成二进制的计算方法
56取余2 (余为0) 的商取余2 (余为0) 反复计算 直至商为1 得出的结果为余的倒序排列(0b为utf-8的固定格式)0b110001
56 0
28 0
14 0
7 1
3 1
1 1
print(bin(56))
二进制转成十进制的计算方法
111000 # 从右向左进行计算(先做幂运算)
0 * 2 ** 0 + 0 * 2 ** 1 + 0 * 2 ** 2 + 1 * 2**3 + 1*2 ** 4 +1 * 2** 5
0 + 0 + 0 + 8 + 16 + 32 =56
print(int("10101",2))
2. 字符串(str)
在python中只要是用引号引起来的就是字符串(str)
加法 -- 同是字符串才能相加
乘法 -- 只能和数字进行相乘
a = "my name's xiaoxiao"
1. 字符串拼接
a = '5'
b = '8'
print(a+b) # '58' 只能和字符串相加
2. 字符串相乘
a = '坚强'*8
print(a) # '坚强坚强坚强坚强坚强坚强坚强坚强'
注释 编码错误
解决方法:
-*-coding:utf-8 -*- #python 2
3. 字符串转义
a = '58'
b = '你好'
c = 'abc'
a1 = int(a) # int 要转换的内容只有带着引号的数字才可以
print(type(a1)) # <class 'int'>
str() # str 要转换的内容没有限制
4. 字符串的索引,切片,步长
字符串,就是由字符组成的串。字符又包括数字、字母、符号等
在python中引号引起来就是字符串
# 字符串是用来存储少量数据(512MB),
#索引(下标)
# name = "meat"
# meat 每一个字母叫做一个元素
5. 索引(下标)msg = '天王盖地虎,小鸡炖蘑菇.'
a = '你好你好' #字符串:存储一些数据
# 0 1 2 3 #从左往右: 0-n #下标
# -4 -3 -2 -1 # 从右往左:-1:(-n) 字符串的长度
print(msg[7]) #'鸡'
print(msg[-5]) #'鸡'
1 class str(): 2 def __getitem__(self, *args, **kwargs): # real signature unknown 3 """ Return self[key]. """ 4 pass
6. 切片
#切片
print(msg[7:9]) #把小鸡打印出来 特性:顾头不顾尾,7为小 起始位置,9为尾 结尾位置.
print(msg[9:7:-1]) #1表示从左往右,-1表示方向从右往左
7. 切片加步长
print(msg[7:9:2]) #小炖 默认不写为1步长.切片的时候起始位置和终止位置都超出的时候不会进行报错
print(msg[1]) #索引查找如果过界就报错,切片的时候就获取到最后一个内容
print(msg[-6:-4]) #把小鸡打印出来 #-6为起始位置 -4为终止位置
3. 字符串方法
1.capitalize(首字母大写)
1 s = 'alex' 2 # 首字母大写 3 s2 = s.capitalize() 4 print(s2) 5 6 """ 7 'Alex' 8 ''"
1 ef capitalize(self): # real signature unknown; restored from __doc__ 2 """ 3 S.capitalize() -> str 4 5 Return a capitalized version of S, i.e. make the first character 6 have upper case and the rest lower case. 7 """ 8 return ""
2. title(每个单词首字母大写)
1 s = 'alex' 2 # 首字母大写 3 s2 = s.capitalize() 4 print(s2) 5 6 """ 7 'Alex' 8 """
1 def title(self): # real signature unknown; restored from __doc__ 2 """ 3 S.title() -> str 4 5 Return a titlecased version of S, i.e. words start with title case 6 characters, all remaining cased characters have lower case. 7 """ 8 return ""
3. upper(全部大写)
1 # 全部大写 2 s = 'abc' 3 s3 = s.upper() 4 print(s2) 5 6 7 """ 8 'ABC' 9 """
1 def upper(self): # real signature unknown; restored from __doc__ 2 """ 3 S.upper() -> str 4 5 Return a copy of S converted to uppercase. 6 """ 7 return ""
4. lower(全部小写)
1 #全部小写 2 a = 'ABC' 3 s4 = s.lower() 4 print(s4) 5 6 """ 7 'abc' 8 """
1 #字符串大小写做验证码 2 my_yzm = 'Z98k' 3 yzm = input("请输入验证码:(Z98k)") 4 if yzm.upper() == my_yzm.upper(): 5 print("验证码正确.") 6 else: 7 print("请重新输入.")
1 def lower(self): # real signature unknown; restored from __doc__ 2 """ 3 S.lower() -> str 4 5 Return a copy of the string S converted to lowercase. 6 """ 7 return ""
5. count(计数)
1 #返回的是数量,计数,字符串里有几个L 2 s == 'alEkLx' 3 print(s.count('L')) 4 5 """ 6 1 7 """
1 def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 2 """ 3 S.count(sub[, start[, end]]) -> int 4 5 Return the number of non-overlapping occurrences of substring sub in 6 string S[start:end]. Optional arguments start and end are 7 interpreted as in slice notation. 8 """ 9 return 0
6. startwith/endwith(以什么开头/结尾)
1 #判断是不是以x结尾 2 print(s.endswith('x')) 3 """ 4 True 5 """ 6 7 #判断是不是以a开头 8 print(s.startswith('a')) 9 10 """ 11 False 12 """
1 def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ 2 """ 3 S.endswith(suffix[, start[, end]]) -> bool 4 5 Return True if S ends with the specified suffix, False otherwise. 6 With optional start, test S beginning at that position. 7 With optional end, stop comparing S at that position. 8 suffix can also be a tuple of strings to try. 9 """ 10 return False
1 def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ 2 """ 3 S.startswith(prefix[, start[, end]]) -> bool 4 5 Return True if S starts with the specified prefix, False otherwise. 6 With optional start, test S beginning at that position. 7 With optional end, stop comparing S at that position. 8 prefix can also be a tuple of strings to try. 9 """ 10 return False
7. find()/index(通过元素找下标)
1 #通过元素查找下标,查找没有的返回-1,从左向右只查一个 2 print(s.find('L')) 3 4 print(s.index('L')) #没有的话报错 ValueError: substring not found
1 def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 2 """ 3 S.find(sub[, start[, end]]) -> int 4 5 Return the lowest index in S where substring sub is found, 6 such that sub is contained within S[start:end]. Optional 7 arguments start and end are interpreted as in slice notation. 8 9 Return -1 on failure. 10 """ 11 return 0
1 def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 2 """ 3 S.index(sub[, start[, end]]) -> int 4 5 Return the lowest index in S where substring sub is found, 6 such that sub is contained within S[start:end]. Optional 7 arguments start and end are interpreted as in slice notation. 8 9 Raises ValueError when the substring is not found. 10 """ 11 return 0
8.format(格式化)
1 s == 'alEkLx' 2 print(s.format()) #alEkLx 3 4 s == 'alEkLx{},{},{}' #按照位置进行填充 5 print(s.format('你好','啊','少年')) # alEkLx你好,啊,少年 6 s == 'alEkLx{0},{2},{1}' #按照索引进行填充 7 print(s.format('你好','啊','少年')) # alEkLx你好,少年,啊 8 s == 'alEkLx{a},{b},{c}' #按照关键字指定内容进行填充 9 print(s.format(a='你好',b='啊',c='少年')) #alEkLx你好,啊,少年
1 def format(self, *args, **kwargs): # known special case of str.format 2 """ 3 S.format(*args, **kwargs) -> str 4 5 Return a formatted version of S, using substitutions from args and kwargs. 6 The substitutions are identified by braces ('{' and '}'). 7 """ 8 pass
9. join(拼接)
1 #插入字符串里面的内容 (可迭代对象) 2 s == 'alEkLx' 3 print(s.join('_')) # 不能这么用 4 print('_'.join(s)) # a_l_E_k_L_x 5 #拼接的符号.join(可迭代的对象)
1 def join(self, iterable): # real signature unknown; restored from __doc__ 2 """ 3 S.join(iterable) -> str 4 5 Return a string which is the concatenation of the strings in the 6 iterable. The separator between elements is S. 7 """ 8 return ""
10. split(分割)
1 #*** 分割 返回的是列表 以空格/换行符(\n)/制表符(\t)进行分割 2 s == 'alEkLx{a},{b},{c}' 3 print(s.split('x')) #['alEkL','{a},{b},{c}'] 4 print(s.split('x',maxspilt=1)) #指定数量
1 def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ 2 """ 3 S.split(sep=None, maxsplit=-1) -> list of strings 4 5 Return a list of the words in S, using sep as the 6 delimiter string. If maxsplit is given, at most maxsplit 7 splits are done. If sep is not specified or is None, any 8 whitespace string is a separator and empty strings are 9 removed from the result. 10 """ 11 return []
11. strip(脱)
1 #***脱_脱掉头尾两边的空格/换行符(\n)/制表符(\t) 2 s == ' alEkLx{a},{b},{c} ' 3 print(s.strip(s)) #alEkLx{a},{b},{c} 4 print(s.strip(' ')) # alEkLx{a},{b},{c} 5 print(s.strip(' a')) # lEkLx{a},{b},{c} 6 s == ' alEkLx{a},{b},{c}a ' 7 print(s.strip(' a')) # lEkLx{a},{b},{c}
1 def strip(self, chars=None): # real signature unknown; restored from __doc__ 2 """ 3 S.strip([chars]) -> str 4 5 Return a copy of the string S with leading and trailing 6 whitespace removed. 7 If chars is given and not None, remove characters in chars instead. 8 """ 9 return ""
12. replace(替换)
1 #替换 第一个放要被替换的,第二个放替换的内容 2 s = 'alEkLx{a},{b},{c}a' 3 print(s.replace('a','s',1)) #'slEkLx{a},{b},{c}s'
1 def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ 2 """ 3 S.replace(old, new[, count]) -> str 4 5 Return a copy of S with all occurrences of substring 6 old replaced by new. If the optional argument count is 7 given, only the first count occurrences are replaced. 8 """ 9 return ""
13. 大小写转换
#大小写转换
print(s.swapcase(s)) #ALeKLX{A},{B},{C}A
14. 居中
name = 'alex'
print(name.center(20,'*')) #***********alex**********
15. is系列
is系列
#判断字符串里面的内容是不是全是阿拉伯数字,但是②不行
print(s,isdigit())
#判断字符串里面是不是汉字和字母
print(s.isalpha())
#判断字符串是不是字母,数字,中文
print(s.isalnum())
#判断字符串是不是十进制
print(s.isdecimal())
16. 编码
#编码 编码集
s1 = s.encode('utf-8')
print(s1)
a = 'alex'
a1 = a.encode('utf-8')
print(a1) #b'alex'
a2 = a.encode('gbk')
pring(a2) #b'alex'
17. 解码
#解码
a3 = s.encode('utf-8')
print(a3.decode('gbk')) # 不能使得
s = 'alex'
s1 = s.encode('utf-8') # 编码 utf-8 包含了ascii
print(s1.decode('gbk')) # 解码 gbk 包含了ascii
# 应用场景: 文件操作 网络传输 网络编程
18. 开辟新的空间
name = "alex"
name1 = "wusir"
print(id(name))
print(id(name1))
print(id(name + name1))
4. 布尔值(bool):
Turs#(真的) False#(假的)
s(变量名) =(赋值) 5(值)
#数字转成布尔值 非0 的都是True
print(bool(55)) #True
print(bool("你好")) #True 不是空的就是True
print(bool("")) #False
#布尔值转换成数字
print(int(True)) #1
print(int(False)) #0
#布尔值转换成字符串
msg = str(True)
print(msg)
print(type(msg)) #True 但是是str的数据类型
#布尔值
print(bool(1)) # 数字非零的就是True 零就是False
print(bool("")) # 字符串不为空就是True ,字符串中没有任何内容就是False
取余2
5. 元组: (tuple )
不可变数据,不能被修改,用来存放一些用户密码** 在配置文件中使用
#元组就是一个不可以修改的列表
tu = (1,2,3,4,'你好啊'')
print(tu[2:5]) #元组切片切出来的是元组
print(tu[2:5:2]) #切片+步长
#元组修改方法 改成列表形式再进行修改
tu = list(tu)
print(tu)
tu = ("你好")
tu = ("你好",) #有逗号的是元组
tu = () #空的是元组
tu = ('12')
print(type(tu)) #数据类型是()中的数据本身
#可以加 可以乘数字
python防脱发技巧