本文共 1883 字,大约阅读时间需要 6 分钟。
字符串是计算机中最常用的数据类型之一,用于存储和处理文本信息。在 Python 中,字符串可以通过单引号、双引号或三引号来表示。
str = 'hello world'print(str)
str = "hello world"print(str)
str = '''helloworld'''print(str)
布尔类型用于表示逻辑值,值为 True 或 False。
is_true = Trueis_false = Falseprint(is_true, is_false)
整数用于表示无 decimal 部分的数值。
num = 42print(num)
浮点数用于表示带有 decimal 部分的数值。
num = 42.5print(num)
数字类型包括整数和浮点数,常用于进行数学运算。
a = 1b = 2c = 3del adel b, cprint(a) # 删除后再使用会报错
int(x) # 将 x 转换为整数float(x) # 将 x 转换为浮点数
import mathabs(-10) # 返回绝对值math.ceil(4.1) # 返回上舍整数
列表是 Python 中的有序集合,允许存储和操作多个元素。
students = ['Alice', 'Bob', 'Charlie']nums = [1, 2, 3, 4, 5]
nums[0] = 'new' # 修改列表元素nums.append('sixth') # 添加新元素del nums[0] # 删除指定位置的元素print(nums) nums = [1, 2, 3, 4, 5]print(nums + [6, 7, 8]) # [1, 2, 3, 4, 5, 6, 7, 8]print(nums * 3) # [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
元组与列表类似,但元组的元素不能修改。
tup1 = ('physics', 'chemistry', 1997, 2000)tup2 = (1, 2, 3, 4, 5) tup3 = tup1 + tup2 # (1, 2, 3, 4, 5, 'physics', 'chemistry', 1997, 2000)print(tup3)
字典是无序的键值对集合,适合用于映射关系。
data = { 'name': 'Alice', 'age': 20, 'class': 'Python'} data['age'] = 30 # 修改已有键的值data['school'] = '编程' # 新增键值对print(data)
日期与时间是 Python 中常用模块,用于处理时间相关操作。
import datetimecurrent_time = datetime.datetime.now()print(current_time)
print(datetime.datetime.strftime(current_time, '%Y-%m-%d %H:%M:%S'))
from datetime import timedeltatoday = datetime.date.today()tomorrow = today + timedelta(days=1)yesterday = today - timedelta(days=1)print(today, tomorrow, yesterday)
以下是一些常用的函数和方法:
math.sqrt(x) # 计算平方根time.strftime(time(), '%Y-%m-%d %H:%M:%S') # 格式化时间datetime.strptime('格式化字符串', '格式') # 字符串转日期time.mktime(datetime.timetuple()) # 日期转时间戳通过以上内容,可以快速了解和掌握 Python 中的基本数据类型及其操作方法。
转载地址:http://farfk.baihongyu.com/