python中的字典、列表和字符串 方法使用总结

26 阅读2分钟

当处理Python中的字典、列表和字符串时,有许多内置函数和方法可以帮助我们进行各种操作。下面是它们的总结:

字典(Dictionary)操作方法和函数总结:

  1. 创建字典

    my_dict = {'key1': 'value1', 'key2': 'value2'}
    
  2. 基本操作

    • 获取值:value = my_dict['key']
    • 添加或更新键值对:my_dict['new_key'] = 'new_value'
    • 删除键值对:del my_dict['key']my_dict.pop('key')
  3. 方法和函数

    • dict.keys(), dict.values(), dict.items(): 分别返回字典的键、值、键值对视图。
    • dict.get(key, default): 获取键的值,如果键不存在则返回默认值。
    • dict.update(other_dict): 将另一个字典的键值对更新到当前字典。
    • dict.pop(key): 删除并返回指定键的值。
    • dict.clear(): 清空字典中的所有元素。

列表(List)操作方法和函数总结:

  1. 创建列表

    my_list = [1, 2, 3, 4, 5]
    
  2. 基本操作

    • 获取元素:element = my_list[index]
    • 切片操作:sublist = my_list[start:end]
    • 添加元素:my_list.append(element)
    • 删除元素:del my_list[index]my_list.remove(element)
  3. 方法和函数

    • list.append(element): 在列表末尾添加元素。
    • list.extend(iterable): 将可迭代对象中的元素添加到列表末尾。
    • list.insert(index, element): 在指定位置插入元素。
    • list.remove(element): 删除列表中第一个匹配的元素。
    • list.pop(index): 删除并返回指定位置的元素。

字符串(String)方法总结:

  1. 基本操作

    • 获取长度:len(my_string)
    • 索引和切片:char = my_string[index]substring = my_string[start:end]
    • 连接字符串:new_string = string1 + string2
    • 分割字符串:parts = my_string.split(separator)
  2. 方法

    • str.upper(), str.lower(), str.capitalize(): 大小写转换。
    • str.strip(), str.lstrip(), str.rstrip(): 去除字符串两侧、左侧或右侧的空白字符。
    • str.startswith(prefix), str.endswith(suffix): 检查字符串是否以指定前缀或后缀开头。
    • str.find(substring), str.index(substring): 查找子字符串第一次出现的位置。
    • str.replace(old, new): 替换字符串中的子串。

这些函数和方法涵盖了在处理字典、列表和字符串时最常见的操作需求。根据具体情况选择合适的方法来操作和处理数据。