python3--基本数据类型和数据结构

本文介绍了Python3中的基本数据类型,包括int、float、bool、complex、str、tuple、list、dict和set。详细讲解了每种类型的转换、特点以及相关操作,如字符串的多种函数、元组的不可变性、列表的动态修改、字典的无序性和集合的去重功能。同时提到了数据类型的内置函数`type()`以及数字和字符串的小数据池概念。
摘要由CSDN通过智能技术生成

数据类型:int、float、bool、complex、str、tuple、list、dict、set

  • 不可变数据类型(可哈希):int、float、bool、complex、str、tuple
  • 可变数据类型(不可哈希):list、dict、set

数据结构tuple、list、dict、set

查看数据类型的内置函数:type(数据)

1.整型int

  内置函数:int()

  str->int,字符串只能是整数字符串,其他都会报错“ValueError”

print(type(10))     # <class 'int'>
# 字符串转换为数字
print(int('10'))  # 10
# 布尔值转换为数字
print(int(True))  # 1

2.浮点型float

 内置函数:float()

print(type(10.2))   # <class 'float'>
print(float('10.2'))  # 10.2

3.布尔型bool

  bool值有True---1,False---0 

  内置函数:bool()

  其他数据类型转为布尔型,值为False:0,0.0,'',[],{},(),set(),None,其他均为True

print(type(True))   # <class 'bool'>
# 整型
print(bool(0))  # False
print(bool(10))  # True
# 浮点型
print(bool(0.0))  # False
print(bool(10.2))  # True 
# 复数
print(bool(10+2j))  # True 
# 字符串型
print(bool(''))    # False
print(bool('  '))  # True
print(bool('0'))   # True
# list
print(bool([]))    # False
# tuple
print(bool(()))    # False
# dict
print(bool({}))
print(dict == type({}))  # True
# set
print(bool(set()))    # False
print(set == type(set()))  # True
# None
print(bool(None))  # False

4.复数complex

  内置函数:complex()

print(type(10+2j))  # <class 'complex'>
print(complex('10+2j'))  # (10+2j)
# 取复数的实部、虚部
com = 10 + 2j
print(com.real,com.imag)  # 10.0 2.0

5.字符串str

  字符串相关函数:capitalize()、upper()、lower()、swapcase()、title()、center()、len()、startwith()、endwith()、find()、    index()、strip()、lstrip()、rstrip()、count()、split()

  int->str,float->str,bool->str,complex->str,使用str()

print(type('hello word'))   # <class 'str'>
# 整型转字符串
print(type(str(10)))  # <class 'str'>
# 浮点型转字符串
print(type(str(10.2)))  # <class 'str'>
# 布尔值转字符串
print(type(str(True)))  # <class 'str'>
# 复数转字符串
print(type(str(10+2j)))  # <class 'str'>
# # 字符串操作
str1 = "this's My dream---"
# 字符串首字母大写
print(str1.capitalize())  # This's my dream---
# 字母全部大写
print(str1.upper())  # THIS'S MY DREAM---
# 字母全部小写
print(str1.lower())  # th
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值