python学习day5——基本数据类型及内置方法

python学习day5——基本数据类型及内置方法

一 引子

​ 数据类型是用来记录事物状态的,而事物的状态是不断变化的(如:一个人年龄的增长(操作int类型) ,单个人名的修改(操作str类型),学生列表中增加学生(操作list类型)等),这意味着我们在开发程序时需要频繁对数据进行操作,为了提升我们的开发效率, python针对这些常用的操作,为每一种数据类型内置了一系列方法。本章的主题就是带大家详细了解下它们,以及每种数据类型的详细定义、类型转换。

二 数字类型int与float

2.1 定义

# 1、定义:
# 1.1 整型int的定义
age=10  # 本质age = int(10)

# 1.2 浮点型float的定义
salary=3000.3  # 本质salary=float(3000.3)

# 注意:名字+括号的意思就是调用某个功能,比如
# print(...)调用打印功能
# int(...)调用创建整型数据的功能
# float(...)调用创建浮点型数据的功能

2.2 类型转换

# 1、数据类型转换
# 1.1 int可以将由纯整数构成的字符串直接转换成整型,若包含其他任意非整数符号,则会报错
>>> s = '123'
>>> res = int(s)
>>> res,type(res)
(123, <class 'int'>)

>>> int('12.3') # 错误演示:字符串内包含了非整数符号.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12.3'
        
# 1.2 float同样可以用来做数据类型的转换
>>> s = '12.3'
>>> res=float(s)
>>> res,type(res)
(12.3, <class 'float'>)

2.3 使用

数字类型主要就是用来做数学运算与比较运算,因此数字类型除了与运算符结合使用之外,并无需要掌握的内置方法

三 字符串

3.1 定义:

# 定义:在单引号\双引号\三引号内包含一串字符
name1 = 'jason'  # 本质:name = str('任意形式内容')
name2 = "lili"  # 本质:name = str("任意形式内容")
name3 = """ricky"""  # 本质:name = str("""任意形式内容""")

3.2 类型转换

# 数据类型转换:str()可以将任意数据类型转换成字符串类型,例如 
>>> type(str([1,2,3])) # list->str
<class 'str'>
>>> type(str({"name":"jason","age":18})) # dict->str
<class 'str'>
>>> type(str((1,2,3)))  # tuple->str
<class 'str'>
>>> type(str({1,2,3,4})) # set->str
<class 'str'>

3.3 使用

3.3.1 优先掌握的操作

>>> str1 = 'hello python!'


# 1.按索引取值(正向取,反向取):
# 1.1 正向取(从左往右)
>>> str1[6]
p
# 1.2 反向取(负号表示从右往左)
>>> str1[-4]
h
# 1.3 对于str来说,只能按照索引取值,不能改
>>> str1[0]='H' # 报错TypeError


# 2.切片(顾头不顾尾,步长)
# 2.1 顾头不顾尾:取出索引为0到8的所有字符
>>> str1[0:9]  
hello pyt
# 2.2 步长:0:9:2,第三个参数2代表步长,会从0开始,每次累加一个2即可,所以会取出索引0、2、4、6、8的字符
>>> str1[0:9:2]  
hlopt 
# 2.3 反向切片
>>> str1[::-1]  # -1表示从右往左依次取值
!nohtyp olleh

# 3.长度len
# 3.1 获取字符串的长度,即字符的个数,但凡存在于引号内的都算作字符)
>>> len(str1) # 空格也算字符
13

# 4.成员运算 in 和 not in    
# 4.1 int:判断hello 是否在 str1里面
>>> 'hello' in str1  
True
# 4.2 not in:判断tony 是否不在 str1里面
>>> 'tony' not in str1 
True

# 5.strip移除字符串首尾指定的字符(默认移除空格)
# 5.1 括号内不指定字符,默认移除首尾空格
>>> str1 = '  life is short!  '
>>> str1.strip()  
life is short!

# 5.2 括号内指定字符,移除首尾指定的字符
>>> str2 = '**tony**'  
>>> str2.strip('*')  
tony

# 6.切分split
# 6.1 括号内不指定字符,默认以空格作为切分符号
>>> str3='hello world'
>>> str3.split()
['hello', 'world']
# 6.2 括号内指定分隔字符,则按照括号内指定的字符切割字符串
>>> str4 = '127.0.0.1'
>>> str4.split('.')  
['127', '0', '0', '1']  # 注意:split切割得到的结果是列表数据类型


# 7.循环
>>> str5 = '今天你好吗?'
>>> for line in str5:  # 依次取出字符串中每一个字符
...     print(line)
...
今
天
你
好
吗
?

3.3.2 需要掌握的操作

1.strip, lstrip, rstrip
>>> str1 = '**tony***'

>>> str1.strip('*')  # 移除左右两边的指定字符
'tony'
>>> str1.lstrip('*')  # 只移除左边的指定字符
tony***
>>> str1.rstrip('*')  # 只移除右边的指定字符
**tony
2.lower(),upper()
>>> str2 = 'My nAme is tonY!'

>>> str2.lower()  # 将英文字符串全部变小写
my name is tony!
>>> str2.upper()  # 将英文字符串全部变大写
MY NAME IS TONY!
3.startswith,endswith
>>> str3 = 'tony jam'

# startswith()判断字符串是否以括号内指定的字符开头,结果为布尔值True或False
>>> str3.startswith('t') 
True
>>> str3.startswith('j')
False
# endswith()判断字符串是否以括号内指定的字符结尾,结果为布尔值True或False
>>> str3.endswith('jam')
True
>>> str3.endswith('tony')  
False
4.格式化输出之format

之前我们使用%s来做字符串的格式化输出操作,在传值时,必须严格按照位置与%s一一对应,而字符串的内置方法format则提供了一种不依赖位置的传值方式

案例:

# format括号内在传参数时完全可以打乱顺序,但仍然能指名道姓地为指定的参数传值,name=‘tony’就是传给{name}
>>> str4 = 'my name is {name}, my age is {age}!'.format(age=18,name='tony')
>>> str4  
'my name is tony, my age is 18!'

>>> str4 = 'my name is {name}{name}{name}, my age is {name}!'.format(name='tony', age=18)
>>> str4  
'my name is tonytonytony, my age is tony!'

format的其他使用方式(了解)

# 类似于%s的用法,传入的值会按照位置与{}一一对应
>>> str4 = 'my name is {}, my age is {}!'.format('tony', 18)
>>> str4 
my name is tony, my age is 18!
# 把format传入的多个值当作一个列表,然后用{索引}取值
>>> str4 = 'my name is {0}, my age is {1}!'.format('tony', 18)
>>> str4
my name is tony, my age is 18!

>>> str4 = 'my name is {1}, my age is {0}!'.format('tony', 18)
>>> str4  
my name is 18, my age is tony!

>>> str4 = 'my name is {1}, my age is {1}!'.format('tony', 18)
>>> str4  
my name is 18, my age is 18!
5.split,rsplit
# split会按照从左到右的顺序对字符串进行切分,可以指定切割次数
>>> str5='C:/a/b/c/d.txt'
>>> str5.split('/',1)
['C:', 'a/b/c/d.txt']  

# rsplit刚好与split相反,从右往左切割,可以指定切割次数
>>> str5='a|b|c'
>>> str5.rsplit('|',1)
['a|b', 'c']
6.join
# 从可迭代对象中取出多个字符串,然后按照指定的分隔符进行拼接,拼接的结果为字符串
>>> '%'.join('hello') # 从字符串'hello'中取出多个字符串,然后按照%作为分隔符号进行拼接
'h%e%l%l%o'
>>> '|'.join(['tony','18','read'])  # 从列表中取出多个字符串,然后按照*作为分隔符号进行拼接
'tony|18|read'
7.replace
# 用新的字符替换字符串中旧的字符
>>> str7 = 'my name is tony, my age is 18!'  # 将tony的年龄由18岁改成73岁
>>> str7 = str7.replace('18', '73')  # 语法:replace('旧内容', '新内容')
>>> str7
my name is tony, my age is 73!

# 可以指定修改的个数
>>> str7 = 'my name is tony, my age is 18!'
>>> str7 = str7.replace('my', 'MY',1) # 只把一个my改为MY
>>> str7
'MY name is tony, my age is 18!'
8.isdigit
# 判断字符串是否是纯数字组成,返回结果为True或False
>>> str8 = '5201314'
>>> str8.isdigit()
True

>>> str8 = '123g123'
>>> str8.isdigit()
False

四 列表

4.1 定义

# 定义:在[]内,用逗号分隔开多个任意数据类型的值
l1 = [1,'a',[1,2]]  # 本质:l1 = list([1,'a',[1,2]])

4.2 类型转换

# 但凡能被for循环遍历的数据类型都可以传给list()转换成列表类型,list()会跟for循环一样遍历出数据类型中包含的每一个元素然后放到列表中
>>> list('wdad') # 结果:['w', 'd', 'a', 'd'] 
>>> list([1,2,3]) # 结果:[1, 2, 3]
>>> list({"name":"jason","age":18}) #结果:['name', 'age']
>>> list((1,2,3)) # 结果:[1, 2, 3] 
>>> list({1,2,3,4}) # 结果:[1, 2, 3, 4]

4.3 使用

4.3.1 优先掌握的操作

# 1.按索引存取值(正向存取+反向存取):即可存也可以取  
# 1.1 正向取(从左往右)
>>> my_friends=['tony','jason','tom',4,5]
>>> my_friends[0]  
tony
# 1.2 反向取(负号表示从右往左)
>>> my_friends[-1]  
5
# 1.3 对于list来说,既可以按照索引取值,又可以按照索引修改指定位置的值,但如果索引不存在则报错
>>> my_friends = ['tony','jack','jason',4,5]
>>> my_friends[1] = 'martthow'
>>> my_friends
['tony', 'martthow', 'jason', 4, 5]


# 2.切片(顾头不顾尾,步长)
# 2.1 顾头不顾尾:取出索引为0到3的元素
>>> my_friends[0:4] 
['tony', 'jason', 'tom', 4]
# 2.2 步长:0:4:2,第三个参数2代表步长,会从0开始,每次累加一个2即可,所以会取出索引0、2的元素
>>> my_friends[0:4:2]  
['tony', 'tom']

# 3.长度
>>> len(my_friends)
5

# 4.成员运算in和not in
>>> 'tony' in my_friends
True
>>> 'xxx' not in my_friends
True

# 5.添加
# 5.1 append()列表尾部追加元素
>>> l1 = ['a','b','c']
>>> l1.append('d')
>>> l1
['a', 'b', 'c', 'd']

# 5.2 extend()一次性在列表尾部添加多个元素
>>> l1.extend(['a','b','c'])
>>> l1
['a', 'b', 'c', 'd', 'a', 'b', 'c']

# 5.3 insert()在指定位置插入元素
>>> l1.insert(0,"first")  # 0表示按索引位置插值
>>> l1
['first', 'a', 'b', 'c', 'alisa', 'a', 'b', 'c']

# 6.删除
# 6.1 del
>>> l = [11,22,33,44]
>>> del l[2]  # 删除索引为2的元素
>>> l
[11,22,44]

# 6.2 pop()默认删除列表最后一个元素,并将删除的值返回,括号内可以通过加索引值来指定删除元素
>>> l = [11,22,33,22,44]
>>> res=l.pop()
>>> res
44
>>> res=l.pop(1)
>>> res
22

# 6.3 remove()括号内指名道姓表示要删除哪个元素,没有返回值
>>> l = [11,22,33,22,44]
>>> res=l.remove(22) # 从左往右查找第一个括号内需要删除的元素
>>> print(res)
None

# 7.reverse()颠倒列表内元素顺序
>>> l = [11,22,33,44]
>>> l.reverse() 
>>> l
[44,33,22,11]

# 8.sort()给列表内所有元素排序
# 8.1 排序时列表元素之间必须是相同数据类型,不可混搭,否则报错
>>> l = [11,22,3,42,7,55]
>>> l.sort()
>>> l 
[3, 7, 11, 22, 42, 55]  # 默认从小到大排序
>>> l = [11,22,3,42,7,55]
>>> l.sort(reverse=True)  # reverse用来指定是否跌倒排序,默认为False
>>> l 
[55, 42, 22, 11, 7, 3]
# 8.2 了解知识:
# 我们常用的数字类型直接比较大小,但其实,字符串、列表等都可以比较大小,原理相同:都是依次比较对应位置的元素的大小,如果分出大小,则无需比较下一个元素,比如
>>> l1=[1,2,3]
>>> l2=[2,]
>>> l2 > l1
True
# 字符之间的大小取决于它们在ASCII表中的先后顺序,越往后越大
>>> s1='abc'
>>> s2='az'
>>> s2 > s1 # s1与s2的第一个字符没有分出胜负,但第二个字符'z'>'b',所以s2>s1成立
True
# 所以我们也可以对下面这个列表排序
>>> l = ['A','z','adjk','hello','hea']
>>> l.sort()
>>> l
['A', 'adjk', 'hea', 'hello','z']

# 9.循环
# 循环遍历my_friends列表里面的值
for line in my_friends:
    print(line) 
'tony'
'jack'
'jason'
4
5

4.3.2 了解操作

>>> l=[1,2,3,4,5,6]
>>> l[0:3:1] 
[1, 2, 3]  # 正向步长
>>> l[2::-1] 
[3, 2, 1]  # 反向步长

# 通过索引取值实现列表翻转
>>> l[::-1]
[6, 5, 4, 3, 2, 1]

猜你喜欢

转载自www.cnblogs.com/snailhuang/p/11798368.html