Python基础之-数据的基本类型及内置方法

数据的基本类型及内置方法


数字类型

  • int (整型)
  • float (浮点型)
# int 用来记录人的年龄,出生年份,学生人数等整数相关的状态

# 定义
age = 18
idcard = 123456789

print('类型:', type(a))

类型: <class 'int'>
# float 用来记录人的身高,体重,薪资等小数相关的状态

# 定义
height = 180.5
weight = 135.5

print('类型:', type(height))
类型: <class 'float'>
# 类型转换

s = "0425"

print(f'{type(int(s))}')

# int可以将由纯整数构成的字符串直接转换成整型,若包含其他任意非整数符号,则会报错

# 十进制转换

print(bin(3))

print(hex(3))

print(oct(3))

# float 

s = "4.25"

print(f'{type(float(s))}')
<class 'int'>
0b11
0x3
0o3
<class 'float'>

数字类型的使用

# 1、数学运算
a = 5
b = 5
c = 5.5 

print(a +c)   # int 和 float 可以相加

res = a + b
print(res)
类型: <class 'int'>
10.5
10
# 2、比较大小
a = 10
b = 5

res = a < b
print(res)
False

字符串 str

# str  用来记录人的名字,家庭住址,性别等描述性质的状态
# 用 单引号、双引号、多引号 都可以定义字符串,在本质上是没有区别的。

# 定义 
name = 'cody'
address = '广东省深圳市'
sex = '男'

print('类型:',type(name))

# 特殊情况
# 字典
info = {'name':'cody', 'age':18}

print("f'姓名:{info['name']}, 年龄:{info['age']}'")
# 这里要注意 引号问题 单引号,双引号
类型: <class 'str'>
f'姓名:{info['name']}, 年龄:{info['age']}'

类型转换

# 类型转换
# str() 可以将任意数据类型转换成 字符串类型

print(type(str([1, 2, 3, 4])))

print(type(str((1, 2, 3, 4))))

print(type(str({'name':'cody', 'age':18})))
<class 'str'>
<class 'str'>
<class 'str'>

str 的使用

# 只能进行"相加"和"相乘"运算 (字符串拼接)

name = 'cody'
age = '18'

print(name + age)  # 字符串拼接  不推荐使用 (jion)
print(name * 3)  # 相乘 = 做了 3 次字符串相加
cody18
codycodycody
str_1 = 'hello cody'

# 按照索引取值

print(f'取出从左往又的第三个值:{str_1[3]}')  # 正向取值 

print(f'取出从右往左的第4个值:{str_1[-4]}')  # 反向取值

# str 只能按照索引取值,不能修改值
取出从左往又的第三个值:l
取出从右往左的第4个值:c
str_1 = 'hello cody'

# 切片操作

# 顾头不顾尾:取出索引为0到4的所有字符
print(f'索引0-4:{str_1[0:4]}')

# 步长:0:6:3,第三个参数3代表步长,会从0开始,每次累加一个3
print(str_1[0:8:3])

# 反向切片
print(str_1[::-1])
索引0-4:hell
hlc
ydoc olleh
str_1 = 'hello cody'

# 获取字符串的个数 len()

print(f'字符串的长度:{len(str_1)}')
字符串的长度:10
str_1 = 'hello cody'

# 成员运算  in 和 not in

# 判断 llo 是否在 str_1 里面

print("llo" in str_1)

# 判断 coding 是否不在 str_1 里面
print("coding" not in str_1)
True
True
str1 = "   hello  cody   "

# strip() 移除字符串首尾指定的字符(默认移除空格)

print(str1.strip())   # 括号内不指定字符,默认移除首尾空白字符(空格、\n、\t)

str2 = "***hello***"
print(str2.strip("*"))   #  括号内指定字符,移除首尾指定的字符
hello  cody
hello
str1 = "hello cody"

# 切分 split()

print(str1.split())   # 括号内不指定字符,默认以空格作为切分符号

str2 = "192.168.1.1"

print(str2.split("."))  # 括号内指定分隔字符,则按照括号内指定的字符切割字符串

#  split切割得到的结果是列表数据类型
['hello', 'cody']
['192', '168', '1', '1']
str1 = "**hello**"

print(str1.strip("*"))   #  移除左右两边的指定字符

print(str1.lstrip("*"))   #  移除左边的指定字符

print(str1.rstrip("*"))   #  移除右边的指定字符

str2 = "HELLO cody"

print(str2.lower())    # 将英文字符串全部变小写

print(str2.upper())    # 将英文字符串全部变大写


str3 = "hello cody"

print(str3.startswith("h"))   # startswith()判断字符串是否以括号内指定的字符开头,结果为布尔值True或False

print(str3.endswith("h"))    # endswith()判断字符串是否以括号内指定的字符结尾,结果为布尔值True或False
hello
hello**
**hello
hello cody
HELLO CODY
True
False
str1 = 'tmp/project/server.run.sh'

print(str1.split('/'))

print(str1.split('/',1))  #  split() 会按照从左到右的顺序对字符串进行切分,可以指定切割次数

str2 = "netstat -ntulp |grep |80"

print(str2.rsplit("|"))

print(str2.rsplit("|", 1))  # rsplit() 刚好与 split() 相反,从右往左切割,可以指定切割次数
['tmp', 'project', 'server.run.sh']
['tmp', 'project/server.run.sh']
['netstat -ntulp ', 'grep ', '80']
['netstat -ntulp |grep ', '80']
# join()   从可迭代对象中取出多个字符串,然后按照指定的分隔符进行拼接,拼接的结果为字符串

str1 = "hello"

print("-".join(str1))    # 从字符串'hello'中取出多个字符串,然后按照 - 作为分隔符号进行拼接


str2 = ["cody", "18", "python"]

print("|".join(str2))  # 从列表中取出多个字符串,然后按照 | 作为分隔符号进行拼接
h-e-l-l-o
cody|18|python
# replace()  # 用新的字符替换字符串中旧的字符

str1 = "cody,age is 18"

print(str1.replace("18", "20"))

print(str1.replace("cody", "coding"))
cody,age is 20
coding,age is 18
# isdigit()  判断字符串是否是纯数字组成,返回结果为True或False

str1 = '13385239645678'

print(str1.isdigit())

str2 = "cody0425"
print(str2.isdigit())

# 最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景,如果要判断中文数字或罗马数字,则需要用到isnumeric。
True
False
# find 从指定范围内查找子字符串的起始索引,找得到则返回数字1,找不到则返回-1

str1 = "hello cody"

print(str1.find("c", 0 ,9))   # 在索引为0和9(顾头不顾尾)的字符中查找字符o的索引

# index()

print(str1.index("c"))


# count()  统计字符串在大字符串中出现的次数

print(str1.count('l'))
6
6
2
# center 

str1 = "hello"

print(str1.center(20,"-"))   # 总宽度为20,字符串居中显示,不够用 - 填充

# ljust

print(str1.ljust(20, "@"))   # 总宽度为20,字符串左对齐显示,不够用 @ 填充

# rjust 

print(str1.rjust(20, "@"))   # 总宽度为20,字符串右对齐显示,不够用 @ 填充
-------hello--------
hello@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@hello
# captalize():首字母大写 

str1 = "hello"

print(str1.capitalize())   

# swapcase():大小写翻转

str2 = "HELLO cody"

print(str2.swapcase())

# title():每个单词的首字母大写

print(str2.title())
Hello
hello CODY
Hello Cody
# isalnum()   字符串中既可以包含数字也可以包含字母

str1 = "cody0425"
print(str1.isalnum())


# isalpha() #字符串中只包含字母
print(str1.isalpha())


# islower()  # 字符串是否是纯小写
print(str1.islower())


# isupper()  # 字符串是否是纯大写
print(str1.isupper())


# isspace()  # 字符串是否全是空格
print(str1.isspace())


# istitle()  # 字符串中的单词首字母是否都是大写

print(str1.istitle())
True
False
True
False
False
False

列表 list

# list 专门用来记录多个同种属性的值

# 定义  []

info = ['cody', '18']

类型转换

# 能被for循环遍历的数据类型都可以传给list()转换成列表类型,list()会跟for循环一样遍历出数据类型中包含的每一个元素然后放到列表中

list 的使用

# 1、列表类型是用索引来对应值,索引代表的是数据的位置,从0开始计数

info = ['cody', '18', 'Python']

print(info.index('cody'))  # 查看 列表 info 中 ‘cody’ 的索引

print(info[0]) # 正向取(从左往右)
print(info[-2]) # 反向取(负号表示从右往左)

info[1] = "coding"
print(info)

# 2、列表可以嵌套,嵌套取值如下

info = [['cody', 18], ['coding', 20, ['篮球']]]
print(info[1][2])
0
cody
18
['cody', 'coding', 'Python']
['篮球']
# 切片

info = ['cody', '18', 'Python', 'java', 'c#']

print(info[0:2])   # 顾头不顾尾:取出索引为0到3的元素

print(info[0:4:2])  # 步长:0:4:2,第三个参数2代表步长,会从0开始,每次累加一个2即可,所以会取出索引0、2的元素


# len()  长度
print(len(info))


# 成员运算符  in not in

print('cody' in info)

print("coding" not in info)
['cody', '18']
['cody', 'Python']
5
True
True
# 添加操作

info = ['cody', '18', 'Python']


# append()  列表尾部追加元素

info.append("java")
print(info)

# extend() 一次性在列表尾部添加多个元素
info.extend(['goland', 'c#', 'ruby'])
print(info)


# insert()在指定位置插入元素
info.insert(5, 'php')
print(info)
['cody', '18', 'Python', 'java']
['cody', '18', 'Python', 'java', 'goland', 'c#', 'ruby']
['cody', '18', 'Python', 'java', 'goland', 'php', 'c#', 'ruby']
# 删除
# del()    删除索引为2的元素
info = ['cody', '18', 'Python', 'java', 'goland', 'php', 'c#', 'ruby']

del info[1]
print(info)


# pop()    默认删除列表最后一个元素,并将删除的值返回,括号内可以通过加索引值来指定删除元素
print(info.pop())


# remove()    括号内指名道姓表示要删除哪个元素,没有返回值
print(info.remove("Python"))
print(info)
['cody', 'Python', 'java', 'goland', 'php', 'c#', 'ruby']
ruby
None
['cody', 'java', 'goland', 'php', 'c#']
# reverse()   颠倒列表内元素顺序

info = ['cody', '18', 'Python', 'java', 'goland', 'php', 'c#', 'ruby']

print(info.reverse())
print(info)


# sort()    给列表内所有元素排序
info1 = [1, 5, 3, 9, 6]
info1.sort()
print(info1)


# sort(reverse=True)  # reverse用来指定是否跌倒排序,默认为False
info1.sort(reverse=True)
print(info1)
None
['ruby', 'c#', 'php', 'goland', 'java', 'Python', '18', 'cody']
[1, 3, 5, 6, 9]
[9, 6, 5, 3, 1]
# 数字类型直接比较大小,但其实,字符串、列表等都可以比较大小
# 原理相同:都是依次比较对应位置的元素的大小,如果分出大小,则无需比较下一个元素

l1 = [1, 3, 4]
l2 = [2]
print(l2 > l1)

# 字符之间的大小取决于它们在ASCII表中的先后顺序,越往后越大
s1 = 'abc'
s2 = 'qwe'
print(s2 > s1)
True
True
l = [1, 2, 3, 4, 5, 6]

print(l[0:3:1])   # 正向步长

print(l[2::-1])   # 反向步长

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

元祖 tuple

# tuple 元组与列表类似,也是可以存多个任意类型的元素,不同之处在于元组的元素不能修改,即元组相当于不可变的列表,用于记录多个固定不允许修改的值,单纯用于取

# 定义 tuple('cody', 'Python') 

类型的转换

# 但凡能被for循环的遍历的数据类型都可以传给tuple()转换成元组类型

print(tuple('wdad'))
print(tuple([1,2,3]))
print(tuple({"name":"jason","age":18}))
print(tuple((1,2,3)))
print(tuple({1,2,3,4}))
# tuple()会跟for循环一样遍历出数据类型中包含的每一个元素然后放到元组中
('w', 'd', 'a', 'd')
(1, 2, 3)
('name', 'age')
(1, 2, 3)
(1, 2, 3, 4)

tuple 的使用

tuple1 = ('cody', 'python', '18')
print(tuple1[0])
print(tuple1[-1])

tuple1[0]= 'coding'
print(tuple1)
# TypeError: 'tuple' object does not support item assignment

# 按索引取值(正向取/反向取):只能取,不能改 
cody
18



---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-154-bab0f2781e6e> in <module>
      3 print(tuple1[-1])
      4 
----> 5 tuple1[0]= 'coding'
      6 print(tuple1)


TypeError: 'tuple' object does not support item assignment
# 切片

tuple2 = ('cody', 18, 'python', 'java')

print(tuple2[0:4:2])  # 顾头部顾尾,步长


# 长度 len()

print(len(tuple2))


# 成员运算符

print('coding' in tuple2)

print("coding" not in tuple2)
('cody', 'python')
4
False
True

字典 dict

# dict 字典类型是用key来对应值(value),key可以对值(value)有描述性的功能,通常为字符串类型, value 可以是任意类型, key 必须是不可变类型

# 定义  {}

info = {'name':'cody', 'age':18, 'hobby':'篮球'}

类型转换

info = dict(id = 100, name = 'cody')
print(info)
{'id': 100, 'name': 'cody'}

dict 的使用

# 1、通过 key 取 value

info = {'name':'cody', 'age':18, 'hobby':'篮球'}

print(info['name'])
print(info['hobby'])

# 2、字典可以嵌套,嵌套取值

info = [
    {'name':'cody', 'age':18, 'hobby':['python', 'java']},
    {'name':'coding', 'age':20, 'hobby':['java','c#']}
]

print('coding 的爱好是:', info[1]['hobby'][1])

# 字典赋值

info1 = {'name':'cody', 'age':18, 'hobby':'篮球'}

info1['like'] = 'java'
print(info1)

info1['like'] = 'C++'
print(info1)


# 长度

print(f'长度是:{len(info1)}')


# 成员运算符

info2 =  {'name':'cody', 'age':18, 'hobby':'篮球'}

print('cdoing' in info2) # 判断某个值是否是字典的key

# 删除

info3 =  {'name':'cody', 'age':18, 'hobby':'篮球'}

print(info3.pop('hobby'))
print(info3)
cody
篮球
coding 的爱好是: c#
{'name': 'cody', 'age': 18, 'hobby': '篮球', 'like': 'java'}
{'name': 'cody', 'age': 18, 'hobby': '篮球', 'like': 'C++'}
长度是:4
False
篮球
{'name': 'cody', 'age': 18}
#  键keys(),值values(),键值对items()

info = {'name':'cody', 'age':18, 'hobby':'篮球'}

print(info.keys())  # 获取字典的所有key

print(info.values())  # 获取字典所有的 value

print(info.items())  # 获取字典的 key 和 value
dict_keys(['name', 'age', 'hobby'])
dict_values(['cody', 18, '篮球'])
dict_items([('name', 'cody'), ('age', 18), ('hobby', '篮球')])
# 循环

info = {'name':'cody', 'age':18, 'hobby':'篮球'}


# 默认遍历的是字典的key
for key in info:
    print(key)

    
print('-'* 30)
# 只遍历 key
for key in info.keys():
    print(key)
    
    
print('-'* 30)
# 只遍历 value    
for key in info.values():
    print(key)
    
    
print('-'* 30)
# 遍历 key 和 value   
for key in info.items():
    print(key)
name
age
hobby
------------------------------
name
age
hobby
------------------------------
cody
18
篮球
('name', 'cody')
('age', 18)
('hobby', '篮球')
# .get()

info = {'name':'cody', 'age':18, 'hobby':'篮球'}

print(info.get("name"))  # key存在,则获取key对应的value值

print(info.get('like','key 不存在'))   #  key不存在时,设置默认返回的值


# pop
print(info.pop('age'))   # 删除指定的key对应的键值对,并返回值
print(info)


print(info.popitem())   # 随机删除一组键值对,并将删除的键值放到元组内返回
print(info)
cody
key 不存在
18
{'name': 'cody', 'hobby': '篮球'}
('hobby', '篮球')
{'name': 'cody'}
# update()  # 用新字典更新旧字典,有则修改,无则添加

info = {'name': 'cody'}
info1 = {'name': 'cody', 'hobby': '篮球'}

info.update(info1)

print(info)
{'name': 'cody', 'hobby': '篮球'}
# fromkyes()

info =  {'name': 'cody'}

dic = info.fromkeys(['age', 'like'],[])
print(dic)
{'age': [], 'like': []}
# setdefault()

info =  {'name': 'cody'} 

# key不存在则新增键值对,并将新增的value返回
print(info.setdefault('age', 18))

# 字典中新增了键值对
print(info)


info1 =  {'name': 'cody'}
# key存在则不做任何修改,并返回已存在key对应的value值
print(info1.setdefault('name','coding'))
print(info1)
18
{'name': 'cody', 'age': 18}
cody
{'name': 'cody'}

集合

# 集合、list、tuple、dict一样都可以存放多个值,但是集合主要用于:去重、关系运算

# 定义:
#   在 {} 内用逗号分隔开来多个元素,
#    每个集合必须是不可变类型
#    集合内没有重复的元素
#    集合内无序

set1 = {1, 2, 3, 4}   # 等于 s = set({1, 2, 3, 4})

# 注意1:列表类型是索引对应值,字典是key对应值,均可以取得单个指定的值,而集合类型既没有索引也没有key与值对应,
#  所以无法取得单个的值,而且对于集合来说,主要用于去重与关系元素,根本没有取出单个指定值这种需求。


# 如何区分 字典 和 集合
d = {}  # 这是空字典

s = set()  # 这是定义空集合

类型准换

# 能被for循环的遍历的数据类型(强调:遍历出的每一个值都必须为不可变类型)都可以传给set()转换成集合类型

s = set([1, 2, 3, 4])

s1 = set((1, 2, 3, 4))

s2 = set({'name':'cody'})

s3 = set('cody')


print(s)
print(type(s))

print(s1)
print(type(s1))

print(s2)
print(type(s2))

print(s3)
print(type(s3))   # 集合是无序的
{1, 2, 3, 4}
<class 'set'>
{1, 2, 3, 4}
<class 'set'>
{'name'}
<class 'set'>
{'y', 'o', 'd', 'c'}
<class 'set'>

使用

set1 = {'cody', '18', 'python', 'java'}
set2 = {'coding', '20', 'python', 'java'}


# 合集/并集(|)
print(set1 | set2)

# 交集(&)
print(set1 & set2)

# 差集(-)
print(set1 - set2)
print(set2 - set1)

# 对称差集(^)
print(set1 ^ set2)

# 等值
print(set1 == set2)


# 父集: 一个集合是否包含另一个集合
print(set1 > set2)

# 子集
print(set1 < set2)
{'java', '18', 'cody', 'python', '20', 'coding'}
{'java', 'python'}
{'18', 'cody'}
{'coding', '20'}
{'18', 'cody', '20', 'coding'}
False
False
False
# 去重

# 1. 只能针对不可变类型
# 2. 集合本身是无序的,去重之后无法保留原来的顺序

L = [1, 2, 4, 2, 4, 5, 6]
s = set(L)
print(s)

l1 = []
for i in L:
    if i not in l1:
        l1.append(i)

print(l1)  # 重重且保证了排序
{1, 2, 4, 5, 6}
[1, 2, 4, 5, 6]

布尔 bool

# bool  用来记录真假这两种状态

# 定义:

a = True
b = False

print(type(a))
print(b)

# 通常用来当作判断的条件
<class 'bool'>
False

数据类型转换

# 转整数 int()

a = '10'  # int 只能将纯数字的字符串转成整型

# b = int('10.5')

print(type(int(a)))
# print(type(b))
# ValueError: invalid literal for int() with base 10: '10.5'

# 转字符串 str()

age = 10

print(type(str(age)))

# 将字符串形式的数据,转换为原本的a类型 eval()
str1 = '135.5'
print(type(eval(str1)))
<class 'int'>
<class 'str'>
<class 'float'>

可变和不可变类型

# 可变类型:   值改变,  id不变  可以说明改的是 值

# 不可变类型:  值改变  id 也改变   可以说明 是产生了新的值 ,没有改变原值, 原值 是不可修改


# int  是 不可变类型
a = 10
print(f'10的id:{id(a)}')

a = 11
print(f'12的id:{id(a)}')


# float 是 不可变类型
b = 1.1
print(f'1.1的id:{id(b)}')

b = 1.2
print(f'1.2的id:{id(b)}')


# str 是 不可变类型
c = 'cody'
print(f'cody的id:{id(c)}')

c = 'coding'
print(f'coding的id:{id(c)}')

# bool 是 不可变类型


# list 是 可变类型
l1 = ['cody', 'coding']
print(f'l1的id:{id(l1)}')

l1[0] = ['java']
print(f'改值之后的id{id(l1)}')


# dict 是 可变类型
dict1 ={'name': 'cody', 'age': 20}
print(f'dict1的id:{id(dict1)}')

dict1['name'] = 'coding'
print(f'改值之后的id{id(dict1)}')
      

# 不可变类型 : int、 str 、float 、bool
# 可变类型: list 、 dict
10的id:10914784
12的id:10914816
1.1的id:139977420236240
1.2的id:139977420236792
cody的id:139977415341144
coding的id:139977077654336
l1的id:139977416854792
改值之后的id139977416854792
dict1的id:139977416550008
改值之后的id139977416550008

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值