基本数据类型(一)
常用数据类型
Python中有六个常见的数据类型:
Number(数字)
String(字符串)
List(列表)
Tuple(元祖)
Set(集合)
Dictionary(字典)
在六个常见的数据类型中:
不可变数据(三个):Number(数字)、String(字符串)、Tuple(元祖)
可变数据(三个):List(列表)、Dictionary(字典)、Set(集合)
数字(Number)
整数(int)
整数是完整的的数字、正数或负数,没有小数,长度不限,如:
age = 23 birthday = 19970302 score = -3
浮点数(float)
浮动或浮点数是包含小数的正数或负数,也可以是带有'e'或‘E’的科学计数法,如:
height = 178.5 weight = 120.6 earth_radius = 6.37e5
整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的,二浮点数运算则可能会有四舍五入的误差
数值运算
>>>5 + 4 # 加法 9 >>> 4.3 - 2 # 减法 2.3 >>> 3 * 7 # 乘法 21 >>> 2 / 4 # 除法,得到一个浮点数 0.5 >>> 2 // 4 # 除法,得到一个整数 0 >>> 17 % 3 # 取余 2 >>> 2 ** 5 # 乘方 32
注意:
Python可以同时为多个变量赋值,如: a,b = 1,2
一个变量可以通过赋值指向不同类型的对象
数值的除法包括两个运算符:/返回一个浮点数,//返回一个整数,但//返回的不一定是整数类型,它与分母分子的数据类型有关:
>>> 7//3 2 >>> 7.0//3 2.0 >>> 7//3.0 2.0
在混合计算时,Python会把整型转换为浮点数:
>>> 3*3/1.5 6.0 >>> 7.0/2 3.5
数学函数
>>>abs(-10) # 返回数字的绝对值 10 >>>max(-2,2,6,8,10) # 返回给定参数的最大值,参数可以为序列 10 >>>min(-2,2,6,8,10) # 返回给定参数的最小值,参数可以为序列 -2
字符串(str)
字符串是以单引号'或双引号"括起来的任意文本,如:
a = 'hello' b = "world"
可以使用三个引号或三个双引号将多行字符串赋值给变量,如:
a = '''
Python is a widely used general-purpose, high level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. ''' b = """Python is a widely used general-purpose, high level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. """
转义字符
使用'\'转义特殊字符,如果你不想让反斜杠发生转义,可以在字符串前面添加一个‘r’,表示原始字符串:
>>> print('hello\nworld') hello world >>> print(r'hello\nworld') hello\nworld
访问字符串中的值
要访问字符串中的值,可以用方括号'[]'来截取字符串,如:
>>>a = 'hello world!' >>>print(a[0]) # 获取第一个位置的字符(第一个字符的索引位置为0) h >>>print(a[4]) # 获取第五个位置的字符 o
也可以使用切片来截取一定范围的字符,如:
>>> b = 'hello python' >>> print(b[0:5]) # 获取第一个到第五个字符 hello >>> print(b[2:5]) # 获取第二个到第五个字符 llo >>> print(b[:5]) # 获取前五个字符 hello >>> print(b[-6:]) # 获取倒数六个字符 python >>> print(b[::2]) # 获取从头到尾的字符,并且每两个取一个 hlopto
字符串运算符
>>> 'hello'+'world' # 字符串的连接、相加 'helloworld' >>> 'hello'*5 # 字符串的重复、相乘 'hellohellohellohellohello' >>> 'h' in 'hello' # 如果字符串中包含给定的字符返回True True >>> 'p' not in 'hello' # 如果字符串中不包含给定的字符返回True True
字符串格式化
>>> print("my name is %s i'm %d years old" % ('star',23)) # %s 格式化字符串 %d 格式化整数 my name is star i'm 23 years old
更方便的是Python2.6之后可以使用format()函数格式化字符串,而且format()可以接受不限个参数,位置可以不按顺序:
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world'
也可以设置参数:
>>> print("my name is {name},i'm {age} years old".format(name = 'star',age = 23) ) my name is star,i'm 23 years old >>>dic = {'name':'star','age':23} # 通过字典设置参数 >>> print("my name is {name},i'm {age} years old".format(**dic)) my name is star,i'm 23 years old >>>list = ['star',23] # 通过列表索引设置参数 >>> print("my name is {0[0]},i'm {0[1]} years old".format(list)) # '0'是必须的 my name is star,i'm 23 years old
在Python3.6之后的版本添加了f-string,称之为字面量格式化字符串,是新的格式化字符串的语法。f-string格式化字符串以f开头,后面跟着字符串,字符串的表达式用大括号'{}'包起来,他会将变量或表达式计算后的值替换进去。如:
>>> name = 'starpong' >>> f'hello{name}' # 替换变量 'hellostarpong' >>> f'{1+2}' # 使用表达式 '3' >>> dic = {'name':'star','age':23} >>> f"my name is {dic['name']},i'm {dic['age']} years old" "my name is star,i'm 23 years old"
字符串内建函数
基本函数
# 1.capitalize() 方法将字符串的第一个字母变成大写,其他字母变小写。 >>> s="i'm from future.please studying hard." >>> s.capitalize() "I'm from future.please studying hard." # 2.center(width,fillchar) 方法返回一个指定的宽度width居中的字符串,fillchar为填充的字符,默认为空格。 >>> s = "Star" >>> s.center(20,'*') '********Star********' # 3.count(sub, start= 0,end=len(string)) 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。 >>> s="i'm from future.please studying hard." >>> s.count('a') 2 >>> s.count('a',0,16) 0 # 4.encode(encoding='UTF-8',errors='strict') 方法以指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。 # bytes.decode(encoding="utf-8", errors="strict")方法以指定的编码格式解码 bytes 对象。默认编码为 'utf-8'。 >>> s="请努力学习拜托了" >>> s_utf8 = s.encode("utf-8") >>> s_gbk = s.encode("gbk") >>> utf8_s = s_utf8.decode("utf-8") >>> gbk_s = s_gbk.decode("gbk") >>> s_utf8 b'\xe8\xaf\xb7\xe5\x8a\xaa\xe5\x8a\x9b\xe5\xad\xa6\xe4\xb9\xa0\xe6\x8b\x9c\xe6\x89\x98\xe4\xba\x86' >>> s_gbk b'\xc7\xeb\xc5\xac\xc1\xa6\xd1\xa7\xcf\xb0\xb0\xdd\xcd\xd0\xc1\xcb' >>> utf8_s '请努力学习拜托了' >>> gbk_s '请努力学习拜托了' # 5.endswith(suffix[, start[, end]]) 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回 True,否则返回 False。可选参数 "start" 与 "end" 为检索字符串的开始与结束位置。 # startswith(substr, beg=0,end=len(string)) 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。 >>> s="i'm from future.please studying hard." >>> s.endswith("d.") True >>> s.endswith("d.",20) True >>> s.endswith("i'm") False >>> s.endswith("ture",0,15) True >>> s.startswith("i'") True >>> s.startswith("fu") False >>> s.startswith("fu",9) True # 6.find(str, beg=0, end=len(string)) 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。 # rfind(str, beg=0 end=len(string)) 返回字符串最后一次出现的位置,如果没有匹配项则返回-1。 >>> s="i'm from future.please studying hard." >>> s.find("fu") -1 >>> s.find("fu") 9 >>> s.find("fu",5) 9 >>> s.find("fu",10) -1 >>> s.rfind("fu") 9 >>> s.rfind("a") 33 >>> s.rfind("a",0,17) -1 >>> s.rfind("a",0,25) 19 # 7.index(str, beg=0, end=len(string)) 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与find()方法一样,只不过如果str不在 string中会报一个异常。 # rindex() 返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间。如果没有匹配的字符串会报异常。 >>> s="i'm from future.please studying hard." >>> s.index("fu") 9 >>> s.index("fu",5) 9 >>> s.index("fu",10) Traceback (most recent call last): File "<pyshell#40>", line 1, in <module> s.index("fu",10) ValueError: substring not found >>> s.index("a") 19 >>> s.rindex("a") 33 >>> s.rindex("a",19) 33 >>> s.rindex("a",0,18) Traceback (most recent call last): File "<pyshell#108>", line 1, in <module> s.rindex("a",0,18) ValueError: substring not found # 8.isalnum() 方法检测字符串是否由字母和数字组成。如果至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False >>> s= 'star' >>> s.isalnum() True >>> s = "star1997" >>> s.isalnum() True >>> s = "20200427" >>> s.isalnum() True >>> s = "www.cnblogs.com/star1997" >>> s.isalnum() False # 9. isalpha() 方法检测字符串是否只由字母或文字组成。如果至少有一个字符并且所有字符都是字母或文字则返回 True,否则返回 False。 >>> s = "star" >>> s.isalpha() True >>> s = "star快乐吗" >>> s.isalpha() True >>> s = "star1997" >>> s.isalpha() False >>> s = "www.cnblogs.com/star1997" >>> s.isalpha() False # 10. join(sequence) 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。 >>> s1 = "-" >>> s2 = "" >>> s = "star" >>> s1.join(s) 's-t-a-r' >>> s2.join(s) 'star' # 11.len() 方法返回对象(字符、列表、元组等)长度或项目个数。 >>> s = "star" >>> len(s) 4 # 12.ljust(width[, fillchar]) 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。 # rjust(width[, fillchar]) 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串。 >>> s = "Star" >>> s.ljust(30,"*") 'Star**************************' >>> s.rjust(30,"*") '**************************Star' # 13.lower() 方法转换字符串中所有大写字符为小写。 >>> s = "I'm From Future.Please Studying Hard." >>> s.lower() "i'm from future.please studying hard." # 14.max(str) 方法返回字符串中最大的字符。 # min(str) 方法返回字符串中最小的字符。 >>> s = "I'm From Future.Please Studying Hard." >>> max(s) 'y' >>> min(s) ' ' # 15.replace(old, new[, max]) 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。 >>> s = "I'm From Future.Please Studying Hard." >>> s.replace("Future","Past") "I'm From Past.Please Studying Hard." >>> s.replace("a","b",1) "I'm From Future.Plebse Studying Hard." # 16.split(str="", num=string.count(str)) 通过指定分隔符对字符串进行切片,如果第二个参数 num 有指定值,则分割为 num+1 个子字符串。 >>> s="i'm from future.please studying hard." >>> s.split(" ") ["i'm", 'from', 'future.please', 'studying', 'hard.'] >>> s.split(".") ["i'm from future", 'please studying hard', ''] >>> s.split(" ",2) ["i'm", 'from', 'future.please studying hard.'] >>> s.split("u") ["i'm from f", 't', 're.please st', 'dying hard.'] # 17.strip([chars]) 方法用于移除字符串头尾指定的字符(默认为空格)或字符序列。 # lstrip([chars]) 方法用于截掉字符串左边的空格或指定字符。 # rstrip([chars]) 删除 string 字符串末尾的指定字符(默认为空格)。 >>> s = "123st123ar321" >>> s.strip("12") '3st123ar3' >>> s = "123st123ar321" >>> s.lstrip("12") '3st123ar321' >>> s = "123st123ar321" >>> s.rstrip("12") '123st123ar3' # 18.swapcase() 方法用于对字符串的大小写字母进行转换。 >>> s = "I'm From Future.Please Studying Hard." >>> s.swapcase() "i'M fROM fUTURE.pLEASE sTUDYING hARD." # 19.title() 方法返回"标题化"的字符串,就是说所有单词的首个字母转化为大写,其余字母均为小写。 >>> s="i'm from future.please studying hard." >>> s.title() "I'M From Future.Please Studying Hard." # 注意,非字母后的第一个字母将转换为大写字母: >>> s = "hello m3 and 5g" >>> s.title() 'Hello M3 And 5G' # 20.upper() 方法将字符串中的小写字母转为大写字母。 >>> s.upper() "I'M FROM FUTURE.PLEASE STUDYING HARD." # 21.zfill(width) 方法返回指定长度的字符串,原字符串右对齐,前面填充0。 >>> s = "Star" >>> s.zfill(30) '00000000000000000000000000Star'
其他了解函数
# 1.isdecimal() 方法检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。注意:定义一个十进制字符串,只需要在字符串前添加 'u' 前缀即可。 # isdigit() 方法检测字符串是否只由数字组成。 # isnumeric() 方法检测字符串是否只由数字组成,数字可以是: Unicode 数字,全角数字(双字节),罗马数字,汉字数字。 >>> s1 = "star1997" >>> s2 = "20200427" >>> s1.isdecimal() False >>> s2.isdecimal() True >>> s1.isdigit() False >>> s2.isdigit() True >>> s3 = "四" >>> s4 = "Ⅳ" >>> s2.isnumeric() True >>> s3.isnumeric() True >>> s4.isnumeric() True """ s.isdigit、s.isdecimal 和 s.isnumeric 区别 isdigit() True: Unicode数字,byte数字(单字节),全角数字(双字节) False: 汉字数字,罗马数字,小数 Error: 无 isdecimal() True: Unicode数字,,全角数字(双字节) False: 罗马数字,汉字数字,小数 Error: byte数字(单字节) isnumeric() True: Unicode 数字,全角数字(双字节),汉字数字 False: 小数,罗马数字 Error: byte数字(单字节) """ # 2.islower() 方法检测字符串是否由小写字母组成。 >>> s1="i'm from future.please studying hard." >>> s2 = "I'm From Future.Please Studying Hard." >>> s1.islower() True >>> s2.islower() False # 3.isspace() 方法检测字符串是否只由空白字符组成。 >>> s = " " >>> s1 = " 1 " >>> s.isspace() True >>> s1.isspace() False # 4.istitle() 方法检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。 >>> s1="i'm from future.please studying hard." >>> s2 = "I'M From Future.Please Studying Hard." >>> s1.istitle() False >>> s2.istitle() True # 5.isupper() 方法检测字符串中所有的字母是否都为大写。 >>> s1 = "I'M FROM FUTURE.PLEASE STUDYING HARD." >>> s2 = "I'M From Future.Please Studying Hard." >>> s1.isupper() True >>> s2.isupper() False # 6.expandtabs(tabsize=8) 方法把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8。 >>> s = "i'm from future.\tplease studying hard." >>> s.expandtabs() "i'm from future. please studying hard." >>> s.expandtabs(16) "i'm from future. please studying hard." >>> s.expandtabs(2) "i'm from future. please studying hard."
注意:所有字符串方法都返回新值,他们并不会更改原始字符串。
列表(list)
创建一个列表,只要把用逗号分隔的不同的数据项使用方括号括起来,如: list = ['Star','male',23]
访问列表中的值
使用下标索引来访问列表中的值,同样你也可以使用方括号的形式姐却字符,如:
>>> list = ['Star','Male',23,'play game'] >>> print(list[0]) Star >>> print(list[0:2]) ['Star', 'Male']
更改列表中的值
使用索引号来更改特定项目的值,如:
>>> l = ['apple','banana','cherry'] >>> l[1] = 'mango' >>> print(l) ['apple', 'mango', 'cherry']
列表脚本操作符
列表对‘+’和‘*’的操作符与字符串相似。‘+’用于组合列表,‘*’用于重复列表,如:
>>> print([1,2,3]+[4,5,6]) [1, 2, 3, 4, 5, 6] >>> print(['hi']*5) ['hi', 'hi', 'hi', 'hi', 'hi'] >>> print(3 in [1,2,3,4,5]) True >>> print(3 not in [1,2,3,4,5]) False
列表的嵌套
使用嵌套列表即在列表里创建其他列表,如:
>>> list1 = ['a','b','c'] >>> list2 = [1,2,3,4] >>> x = [list1,list2] >>> x [['a', 'b', 'c'], [1, 2, 3, 4]] >>> x[0] ['a', 'b', 'c'] >>> x[0][1] 'b'
列表的函数&方法
列表包含以下函数:
>>> list1 = [11,22,78,90,100,101,222] >>> print(len(list1)) # 列表元素个数 7 >>> print(max(list1)) # 返回列表元素最大值 222 >>> print(min(list1)) # 返回列表元素最小值 11
列表的添加方法:
>>> l = ['apple','banana','cherry'] >>> l.append('orange') # append()方法是在列表末尾追加元素 >>> print(l) ['apple', 'banana', 'cherry', 'orange'] >>>l.insert(1,'pear') # insert()方法是在指定索引处添加元素 >>>print(l) ['apple', 'pear', 'banana', 'cherry', 'orange'] >>>l2 = ['watermelon',‘strawberry’] >>> l.extend(l2) # extend()方法用于在列表末尾一次性追加另一个序列中的多个值 >>> print(l) ['apple', 'pear', 'banana', 'cherry', 'orange', 'watermelon', 'strawberry']
列表的删除方法:
>>> l = ['apple', 'pear', 'banana', 'cherry', 'orange', 'watermelon', 'strawberry'] >>> l.remove('banana') # remove()方法删除指定的项目 >>> print(l) ['apple', 'pear', 'cherry', 'orange', 'watermelon', 'strawberry'] >>> l.pop() # pop()方法删除指定的索引(如果未指定索引,则删除最后一项) 'strawberry' >>> print(l) ['apple', 'pear', 'cherry', 'orange', 'watermelon'] >>> del l[1] # del 删除指定索引(如果未指定索引,则删除完整的列表) >>> print(l) ['apple', 'cherry', 'orange', 'watermelon'] >>> l.clear() # clear()方法是清空列表 >>> print(l) []
其他方法:
>>> l = ['apple', 'pear', 'banana', 'cherry', 'orange', 'watermelon', 'apple'] >>> print(l.count('apple')) # count()方法用于统计某个元素再列表中出现的次数 2 >>> print(l.count('banana')) 1 >>> print(l.index('apple')) # index()方法用于从列表找出某个值第一个匹配的索引位置 0 >>> l.reverse() # reverse()方法用于反向列表中元素 >>> print(l) ['apple', 'watermelon', 'orange', 'cherry', 'banana', 'pear', 'apple'] >>> l.sort() # sort()方法用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数 >>> print(l) ['apple', 'apple', 'banana', 'cherry', 'orange', 'pear', 'watermelon'] >>> l1 = l.copy() # copy()方法用于复制列表,类似于a[:] >>> print(l1) ['apple', 'apple', 'banana', 'cherry', 'orange', 'pear', 'watermelon']
posted on 2020-04-16 10:06 MidSummer丶 阅读(236) 评论(0) 收藏 举报
浙公网安备 33010602011771号