Python数据类型内置方法

  • 本篇文章会详细介绍八大数据类型内置方法的详细使用。
  • 会把每种数据类型的的内置方法总结出来。

【一】整型

【1】定义

num = 10 print(num)

【2】使用

# 加减乘除 v1 = 4 v2 = 8 v3 = v1 + v2

【3】进制转换

[1]十进制转二进制:bin()

  • 将整数转换为二进制表示,返回一个字符串。
num = 42 binary_representation = bin(num) print(binary_representation) # 输出:'0b101010'

[2]十进制转八进制:oct()

  • 将整数转换为八进制表示,返回一个字符串。
num = 42 octal_representation = oct(num) print(octal_representation) # 输出:'0o52'

[3]十进制转十六进制:hex()

  • 将整数转换为十六进制表示,返回一个字符串。
num = 42 hexadecimal_representation = hex(num) print(hexadecimal_representation) # 输出:'0x2a'

[4]其它进制转十进制:int()

  • int() 函数支持将不同进制的字符串转换为十进制整数。主要的进制包括:
    • 二进制(以 '0b' 或 '0B' 开头)
    • 八进制(以 '0o' 或 '0O' 开头)
    • 十六进制(以 '0x' 或 '0X' 开头)
  • 你可以根据需要选择不同的进制进行转换。
binary_str = '0b101010' decimal_num = int(binary_str, 2) print(decimal_num) # 输出:42 octal_str = '0o52' decimal_num = int(octal_str, 8) print(decimal_num) # 输出:42 hexadecimal_str = '0x2a' decimal_num = int(hexadecimal_str, 16) print(decimal_num) # 输出:42
  • 在这些例子中,字符串的前缀表明了不同的进制

【二】浮点型

【1】定义

float_num = 3.14

【2】使用

# 加法 result_add = 3.14 + 2.5 # 减法 result_subtract = 5.7 - 1.2 # 乘法 result_multiply = 2.0 * 3.5 # 除法 result_divide = 8.0 / 4.0 # 取整 rounded_number = round(3.14159) # isdigit: bytes, unicode判断数字类型 num1 = b'4' # bytes num2 = '4' # unicode,Python 3 中不需要在字符串前加 'u' num3 = '四' # 中文数字 num4 = 'Ⅳ' # 罗马数字 print(num1.isdigit()) # True print(num2.isdigit()) # True print(num3.isdigit()) # False print(num4.isdigit()) # False # 判断小数类型(isdecimal) print(num2.isdecimal()) # True print(num3.isdecimal()) # False print(num4.isdecimal()) # False # isdecimal: unicode(bytes 类型没有 isdecimal 方法) # 判断数字类型(isnumeric) # isnumeric: unicode, 中文数字, 罗马数字(bytes 类型没有 isnumeric 方法) print(num2.isnumeric()) # True print(num3.isnumeric()) # True print(num4.isnumeric()) # True # 无法判断浮点数 # 这三种方法无法判断浮点数 num5 = '4.3' print(num5.isdigit()) # False print(num5.isdecimal()) # False print(num5.isnumeric()) # False

【三】布尔类型

【1】定义

布尔值的表示只有两种方法:真或者假 True、False

【2】使用

is_name = False is_Bill = True print(is_Bill,is_name)

【四】字符串

  • 字符串,我们平时会用他来表示文本信息。例如:姓名、地址、自我介绍等。
  • 在Python中,字符串类型使用单引号或双引号、三引号来定义。

【1】定义

字符串不可被修改

user = "你的名字叫什么?" name = "Hello,world" # 三个引号,可以支持多行/换行表示一个字符串,其他的都只能在一行中表示一个字符串。 multi_line_str = ''' This is a multi-line string in Python. '''

【2】使用

1.字符串拼接 str1 = "hello" str2 = "world" result = str1 + ' '+ str2 print(result) # hello world 2.索引取值 str = "hello,world" result = str print(result[0]) print(result[-1]) # h # d 3.切片 str = "hello,world" result = str print(result[0:5]) # hello 步长: str = "hello,world" result = str print(result[0:5:2]) # hlo str = "hello,world" result = str print(result[-1:-4:-1]) #dlr 4.计算长度(lenstr = "hello,world" result = len(str) print(result) # 11 5.成员运算 in not in str = "hello,world" result = "hello" in str text = "world" not in str print(result) print(text) # True # False 6.去除空格 左和右 strip() lstrip() rstrip() name = " H e l l o啊,树哥 " result = name.strip() print(result) name = " H e l l o啊,树哥 " result = name.lstrip() print(result) name = " H e l l o啊,树哥 " result = name.rstrip() print(result) 7.切分,得到一个新的列表 split char = "BB,二牛" user = char.split(',') print(user)# ['BB', '二牛'] 8.遍历字符串 for text = 'apple' for char in text: print(char) # a # p # p # l # e 9.字符串重复 * text = 'apple' data = text * 3 print(data) 10.大小写转换 upper() lower() user = "my name is oliver queen" data = user.upper() print(user) print(data) # my name is oliver queen # MY NAME IS OLIVER QUEEN 字符串变小写,得到一个新字符串 user = "MY NAME IS OLIVER QUEEN" data = user.lower() print(user) print(data) 11.判断字符开头 startswith() str_one = "hello," result = str_one.startswith("he") print(result) # 值为True # 案例 v1 = input("请输入住址:") if v1.startswith("北京市"): print("北京人口") else: print("非北京人口") 12.判断字符结尾 endswith() name = "rose" result = name.endswith("se") print(result) #结果是True 13.格式化输出 %s %d f+{} format # 格式化字符串,得到新的字符串 # 前两个在之前文章介绍过,这次以format为主 name = "{0}的喜欢干的工作有很多,例如{1}、{2}、{3}" data = name.format("老王","空姐","司机","老师") print(data) 14.拼接join res_1 = '%'.join('hello') # 从字符串'hello'中取出多个字符串,然后按照%作为分隔符号进行拼接 print(res_1) # h%e%l%l%o res_2 = '|'.join(['bobo', '18', 'read']) # 从列表中取出多个字符串,然后按照*作为分隔符号进行拼接 print(res_2) # bobo|18|read 15.替换replace data = "你是个好人,但是好人不合适我" value = data.replace("好人","贱人") print(data) # "你是个好人,但是好人不合适我" print(value) # "你是个贱人,但是贱人不合适我" # 案例 char_list = ["逗比","二蛋","钢球"] content = input("请输入评论信息:") for item in char_list: content = content.replace(item, "**") print(content) 16.判断类型isdigit str8 = '5201314' res_1 = str8.isdigit() print(res_1) # True str8 = '123g123' res_2 = str8.isdigit() print(res_2) # False #熟悉: 17.统计指定字符在大字符串中出现的次数 count msg = 'tony say hello' # 统计字符串o在大字符串中出现的次数 res = msg.count('o') print(res) # 2 18.填充 center msg = 'tony' # 用字符o将字符串居中 # 总长度为原有字符串长度 + 需要增加的字符长度 # 在原有字符串基础上,剩余的位置用指定字符 - 填充 # 如果填充长度两侧不平衡,则右多左少分配 res = msg.center(len(msg) + 6, '-') print(res) # --tony--- 19.字符串长度要基于给指定字符长度的基础上增加用 0 填充,填充在字符串左侧 zfill msg = 'tony' # 右对齐 # 总长度为原有字符串长度 + 需要增加的字符长度 # 在原有字符串基础上,剩余的位置用指定字符 0 填充 # 填充在原有字符串的左侧 res = msg.zfill(len(msg) + 6) print(res) # 000000tony

【五】列表

列表(list),是一个有序可变的容器,在里面可以存放多个不同类型的元素。

  • 列表是Python中最常用的数据类型之一,用于存储一组有序的元素

【1】定义

# 示例 numbers = [1, 2, 3, 4, 5] names = ['Alice', 'Bob', 'Charlie', 'David'] mixed_list = [1, 'two', 3.0, 'four', 5]

【2】使用

1.类型强转 # 示例 string = 'hello' list_from_string = list(string) print(list_from_string) # 输出: ['h', 'e', 'l', 'l', 'o'] tuple_example = (1, 2, 3) list_from_tuple = list(tuple_example) print(list_from_tuple) # 输出: [1, 2, 3] range_example = range(5) list_from_range = list(range_example) print(list_from_range) # 输出: [0, 1, 2, 3, 4] 2.索引取值 numbers = [1,2,3,4,5] num = numbers[0] print(num) # 1 3.切片 numbers = [1, 2, 3, 4, 5] sliced_numbers = numbers[1:4] print(sliced_numbers) # 输出: [2, 3, 4] 4.计算长度(len# 示例 numbers = [1, 2, 3, 4, 5] length = len(numbers) print(length) # 输出: 5 5.成员运算 in not in # 示例 numbers = [1, 2, 3, 4, 5] contains_3 = 3 in numbers print(contains_3) # 输出: True # 示例 numbers = [1, 2, 3, 4, 5] not_contains_6 = 6 not in numbers print(not_contains_6) # 输出: True 6.增加 append() # 示例 numbers = [1, 2, 3, 4, 5] numbers.append(6) print(numbers) # 输出: [1, 2, 3, 4, 5, 6] 7.一次性添加多个 extend() tools = ["搬砖","菜刀","榔头"] tools.extend([11,22,33]) print(tools) tools = ["搬砖","菜刀","榔头"] weapon = ["AK47","M6"] weapon.extend(tools) print(tools) print(weapon) # ["AK47","M6","搬砖","菜刀","榔头"] 8.指定位置添加insert() 插入,在原列表的指定索引位置插入值 user_list = ["苍老师","有坂深雪","大桥未久"] user_list.insert(0,"马蓉") print(user_list) # ['马蓉', '苍老师', '有坂深雪', '大桥未久'] 9.删除删除指定索引的元素 del # 示例 numbers = [1, 2, 3, 4, 5] del numbers[2] print(numbers) # 输出: [1, 2, 4, 5] 10.默认删除列表最后一个元素,并将删除的值返回,括号内可以通过加索引值来指定删除元素 pop # 示例 numbers = [1, 2, 3, 4, 5] popped_value = numbers.pop(2) print(popped_value) # 输出: 3 print(numbers) # 输出: [1, 2, 4] 11.remove()括号内指名道姓表示要删除哪个元素,没有返回值remove 在原列表中根据值删除(从左到右找到第一个删除)【慎用,里面没有会报错】 user_list = ["马哥","张姐","王姨"] user_list.remove("马哥") print(user_list) user_list = ["马哥","张姐","王姨"] if "马哥" in user_list: user_list.remove("马哥") print(user_list) user_list = ["马哥","张姐","王姨"] while True: if "马哥" in user_list: user_list.remove("马哥") else: break print(user_list) # ['张姐', '王姨'] # ['张姐', '王姨'] # ['张姐', '王姨'] 12.颠倒元素reverse() # 示例 numbers = [1, 2, 3, 4, 5] numbers.reverse() print(numbers) # 输出: [5, 4, 3, 2, 1] 13.元素排序sort() # 示例 numbers = [5, 2, 9, 1, 7] numbers.sort() print(numbers) # 输出: [1, 2, 5, 7, 9] 14.元素排序sorted() # 示例 numbers = [5, 2, 9, 1, 7] sorted_numbers = sorted(numbers) print(sorted_numbers) # 输出: [1, 2, 5, 7, 9] print(numbers) # 输出: [5, 2, 9, 1, 7] 15.遍历循环for while # 示例 fruits = ['apple', 'banana', 'orange'] for fruit in fruits: print(fruit) # 输出: # apple # banana # orange # 示例 fruits = ['apple', 'banana', 'orange'] index = 0 while index < len(fruits): print(fruits[index]) index += 1 # 输出: # apple # banana # orange

【六】字典

  • 字典(Dictionary)是一种无序的数据集合,使用键(key)和值(value)之间的映射关系来存储数据。
  • 字典是Python中唯一的映射类型,其它语言中可能称为关联数组或哈希表。
  • 字典的特点:
    • 字典中的数据是无序的,不能通过索引来访问,而是通过键来访问。
    • 字典中的键必须是不可变的,通常使用字符串、数字或元组作为键。
    • 字典中的值可以是任意类型,包括数字、字符串、列表、字典等。
  • 字典的创建使用花括号 {},并使用冒号 : 分隔键和值。
  • 多个键值对之间使用逗号 , 分隔。

【1】定义

  • 字典(Dictionary)是一种无序的数据集合,使用键(key)和值(value)之间的映射关系来存储数据。
  • 字典是Python中唯一的映射类型,其它语言中可能称为关联数组或哈希表。
  • 字典的特点:
    • 字典中的数据是无序的,不能通过索引来访问,而是通过键来访问。
    • 字典中的键必须是不可变的,通常使用字符串、数字或元组作为键。
    • 字典中的值可以是任意类型,包括数字、字符串、列表、字典等。
  • 字典的创建使用花括号 {},并使用冒号 : 分隔键和值。
  • 多个键值对之间使用逗号 , 分隔。
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'}

【2】使用

1.按照key取值 # 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} print(person_info['name']) # 输出: Dream 2.get取值 # 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} print(person_info.get('name')) # 输出: Dream print(person_info.get('height', 175)) # 输出: 175 3.计算长度(len# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} length = len(person_info) print(length) # 输出: 3 4.成员运算 in not in # 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} print('name' in person_info) # 输出: True print('height' not in person_info) # 输出: True 5.增加键值对 update() # 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} person_info['height'] = 175 print(person_info) # 输出: {'name': 'Dream', 'age': 25, 'gender': 'male', 'height': 175} 6.加值并返回值 setdefault() # 示例 person_info = {'name': 'Tony', 'age': 25} # 使用setdefault()获取键值,如果键不存在,则添加新键值对 gender = person_info.setdefault('gender', 'male') print(gender) # 输出: male print(person_info) # 输出: {'name': 'Tony', 'age': 25, 'gender': 'male'} 7.按键删除 del() # 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} del person_info['age'] print(person_info) # 输出: {'name': 'Dream', 'gender': 'male'} 8.弹出键值对 pop() # 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} popped_value = person_info.pop('age') print(popped_value) # 输出: 25 print(person_info) # 输出: {'name': 'Dream', 'gender': 'male'} 9.清空字典 clear() # 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} person_info.clear() print(person_info) # 输出: {} 10.随机删除键值对 popitem() # 示例 person_info = {'name': 'Tony', 'age': 25, 'gender': 'male'} # 随机删除一个键值对 removed_item = person_info.popitem() print(removed_item) # 输出: ('gender', 'male') print(person_info) # 输出: {'name': 'Tony', 'age': 25} 11.键对keys () # 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} keys = person_info.keys() print(keys) # 输出: dict_keys(['name', 'age', 'gender']) 12.值对 values() # 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} values = person_info.values() print(values) # 输出: dict_values(['Dream', 25, 'male']) 13.键值对 items() # 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} items = person_info.items() print(items) # 输出: dict_items([('name', 'Dream'), ('age', 25), ('gender', 'male')]) 14.遍历循环 for # 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} for key in person_info: print(key) # 输出: # name # age # gender # 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} for value in person_info.values(): print(value) # 输出: # Dream # 25 # male # 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} for key, value in person_info.items(): print(f'{key}: {value}') # 输出: # name: Dream # age: 25 # gender: male 15.字典排序 sorted() # 示例 my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1} # 对字典按键排序,并返回一个列表 sorted_dict = sorted(my_dict.items()) print(sorted_dict) # 输出: [('apple', 5), ('banana', 2), ('grape', 1), ('orange', 8)] # 示例 my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1} # 对字典按值排序,并返回一个列表 sorted_dict = sorted(my_dict.items(), key=lambda x: x[1]) print(sorted_dict) # 输出: [('grape', 1), ('banana', 2), ('apple', 5), ('orange', 8)]

【七】元组

  • 元组(Tuple)是Python中的一种有序、不可变的数据类型。
  • 元组使用小括号()来定义,可以包含任意类型的元素,包括数字、字符串、列表等。

【1】定义

  • 元组(Tuple)是Python中的一种有序、不可变的数据类型。
  • 元组使用小括号()来定义,可以包含任意类型的元素,包括数字、字符串、列表等。
# 使用逗号 my_tuple = 1, 2, 3 # 使用小括号 my_tuple_explicit = (1, 2, 3)

【2】使用

但凡能被for循环的遍历的数据类型都可以传给tuple()转换成元组类型 使用tuple()函数可以将其他可迭代对象转换为元组 1.索引 fruit_tuple = ('apple', 'banana', 'cherry') print(fruit_tuple[1]) # 输出: banana 2.切片 # 示例 fruit_tuple = ('apple', 'banana', 'cherry', 'date', 'elderberry') print(fruit_tuple[1:4]) # 输出: ('banana', 'cherry', 'date') 3.计算长度(len# 示例 fruit_tuple = ('apple', 'banana', 'cherry') print(len(fruit_tuple)) # 输出: 3 4.成员运算 in not in # 示例 fruit_tuple = ('apple', 'banana', 'cherry') print('banana' in fruit_tuple) # 输出: True print('orange' not in fruit_tuple) # 输出: True # 示例 fruit_tuple = ('apple', 'banana', 'cherry') print('orange' not in fruit_tuple) # 输出: True 5.遍历循环 for # 示例 fruit_tuple = ('apple', 'banana', 'cherry') for fruit in fruit_tuple: print(fruit) # 输出: # apple # banana # cherry 6.元组拼接 + # 示例 tuple1 = (1, 2, 3) tuple2 = ('a', 'b', 'c') result_tuple = tuple1 + tuple2 print(result_tuple) # 输出: (1, 2, 3, 'a', 'b', 'c') 7.元组重复 * # 示例 fruit_tuple = ('apple', 'banana', 'cherry') result_tuple = fruit_tuple * 2 print(result_tuple) # 输出: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')

【八】集合

  • 集合(Set)是 Python 中的一种无序且不重复的数据类型。
  • 集合类型的定义使用大括号 {},元素之间使用逗号 , 分隔。

【1】定义

  • 集合(Set)是 Python 中的一种无序且不重复的数据类型。
  • 集合类型的定义使用大括号 {},元素之间使用逗号 , 分隔。
# 示例 my_set = {1, 2, 3, 4, 5} print(my_set) # 输出: {1, 2, 3, 4, 5}
  • 无序性
print(set('dream')) # 第一次 : {'a', 'm', 'r', 'd', 'e'} # 第二次 : {'r', 'd', 'a', 'm', 'e'}
  • 去重性
print(set('dreame')) # 第一次 : {'d', 'e', 'a', 'r', 'm'} # 第二次 : {'e', 'a', 'd', 'r', 'm'}

【2】使用

但凡能被for循环的遍历的数据类型(强调:遍历出的每一个值都必须为不可变类型)都可以传给set()转换成集合类型 1.添加单个元素 add # 示例 my_set = {1, 2, 3} my_set.add(4) print(my_set) # 输出: {1, 2, 3, 4} 2.添加多个元素 update # 示例 my_set = {1, 2, 3} my_set.update([3, 4, 5]) print(my_set) # 输出: {1, 2, 3, 4, 5} 3.删除指定元素 remove # 示例 my_set = {1, 2, 3, 4, 5} my_set.remove(3) print(my_set) # 输出: {1, 2, 4, 5} 4.删除指定元素 discard # 示例 my_set = {1, 2, 3, 4, 5} my_set.discard(3) print(my_set) # 输出: {1, 2, 4, 5} 5.随机删除元素 pop # 示例 my_set = {1, 2, 3, 4, 5} removed_element = my_set.pop() print(removed_element) # 输出: 随机移除的元素 print(my_set) # 输出: 移除后的集合 6.去重 l_old = ['a', 'b', 1, 'a', 'a'] s = set(l_old) # 将列表转成了集合 print(s) # {'b', 'a', 1} l_new = list(s) # 再将集合转回列表 print(l_new) # 去除了重复,但是打乱了顺序 # ['b', 'a', 1] # 针对不可变类型,并且保证顺序则需要我们自己写代码实现,例如 l_second = [ {'name': 'lili', 'age': 18, 'sex': 'male'}, {'name': 'jack', 'age': 73, 'sex': 'male'}, {'name': 'tom', 'age': 20, 'sex': 'female'}, {'name': 'lili', 'age': 18, 'sex': 'male'}, {'name': 'lili', 'age': 18, 'sex': 'male'}, ] new_l_second = [] for dic in l_second: if dic not in new_l_second: new_l_second.append(dic) print(new_l_second) # 结果:既去除了重复,又保证了顺序,而且是针对不可变类型的去重 ''' [ {'name': 'lili', 'age': 18, 'sex': 'male'}, {'name': 'jack', 'age': 73, 'sex': 'male'}, {'name': 'tom', 'age': 20, 'sex': 'female'} ] ''' 7.计算长度 len() # 计算集合长度 length = len(unique_set) print(length) # 输出: 5 8.遍历循环 for my_set = {1, 2, 3, 'a', 'b'} # 遍历集合 for item in my_set: print(item) # 输出: 1 2 3 'a' 'b' 9.成员运算 in not in is_in_set = 'a' in my_set print(is_in_set) # 输出: True is_not_in_set = 6 not in my_set print(is_not_in_set) # 输出: True 集合操作: 1.并集 union() # 示例 set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1.union(set2) print(union_set) # 输出: {1, 2, 3, 4, 5} 2.交集 intersection() # 示例 set1 = {1, 2, 3} set2 = {3, 4, 5} intersection_set = set1.intersection(set2) print(intersection_set) # 输出: {3} 3.差集 difference() # 示例 set1 = {1, 2, 3} set2 = {3, 4, 5} difference_set = set1.difference(set2) print(difference_set) # 输出: {1, 2} 4.对称差集 symmetric_difference() # 示例 set1 = {1, 2, 3} set2 = {3, 4, 5} symmetric_difference_set = set1.symmetric_difference(set2) print(symmetric_difference_set) # 输出: {1, 2, 4, 5} 5.父集 issuperset() set1 = {1, 2, 3, 4, 5} set2 = {2, 4} # 判断 set1 是否是 set2 的父集 is_superset = set1.issuperset(set2) print(is_superset) # 输出: True 6.子集 issubset() set1 = {1, 2, 3, 4, 5} set2 = {2, 4} # 判断 set2 是否是 set1 的子集 is_subset = set2.issubset(set1) print(is_subset) # 输出: True 7.判断 == set1 = {1, 2, 3, 4, 5} set2 = {2, 4} # 判断两个集合是否相等 is_equal = set1 == set2 print(is_equal) # 输出: False

__EOF__

本文作者Fredette
本文链接https://www.cnblogs.com/Fredette/p/17877998.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   Fredette  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示