python之字符串,列表,字典,元组,集合内置方法总结

时间:2022-05-24 03:32:22

数字类型的内置方法

整型/浮点型

+
-
*
/
取余 %
余数取整 //

字符串类型的内置方法

掌握 熟悉 了解
按索引取值 ,strs[0] lstrip,rstrip find,rfind
切片,str[::-1] lower,upper index,rindex
长度,len[strs] startswith,endswith count
成员运算,print{" 'llo' in strs"} rsplit center,ljust,rjust,zfill
移除空白, strs.strip() join expandtabs
切割,strs.split() replace captalize,swapcase,title
循环,for i in strs: isdigit is

掌握

a = "Hello World"

  1. 按索引取值:

    print{a[0]}
    
    # H
    
    '''
    总结:
    1. 索引取值可以根据索引随时拿到字符串中任意一个字符.在工作中经常使用
    '''
  2. 切片

    print{a[::-1]}
    print(a[-1:-6:-1]) # dlroW olleH
    # dlroW '''
    总结:
    1. 切片不仅可以截取字符串中的任意一部分,同时也可以将字符串进行反转操作.
    '''
  3. 长度,len()

    print(len(a))
    
    # 11
    
    '''
    总结:
    1. 经常会根据字符串的长度 获取对应索引.在工作中经常使用.
    '''
  4. 成员运算,in/ not in

    print("ello" in a)
    
    # True
  5. 移除空白,strip,lstrip,rstrip

    b = "  dajiahao!wo jiao panlifu "
    print(b.strip()) # dajiahao!wo jiao panlifu 默认直接删除字符串两端的空白 print(b.strip(" adwuflinp"))
    # jiahao!wo jiao 直接从两端进行删除,只要传参的字符串中包含b字符串两端的字符,即可删除,没有则停止 # lstrip 左移除
    print(b.lstrip())
    print(b.lstrip(" jadu")) # dajiahao!wo jiao panlifu
    # iahao!wo jiao panlifu # rstrip 右移除
    print(b.rstrip())
    print(b.rstrip(" aflui")) # dajiahao!wo jiao panlifu
    # dajiahao!wo jiao pan
  6. 切割, split,rsplit

    print(a.split(" ",1))
    # ['Hello', 'World'] print(a.split("o",2))
    print(a.split("o")) # ['Hell', ' W', 'rld']
    # ['Hell', ' W', 'rld'] # rsplit 右切割
    print(a.rsplit())
    # ['Hel', 'o Wor', 'd']
  7. for循环

    for i in a:
    print(i) '''
    H
    e
    l
    l
    o W
    o
    r
    l
    d
    '''

熟悉

  1. 大小写, lower/upper

    print(a.lower())
    
    # hello world
    
    print(a.upper())
    
    # HELLO WORLD
    
    '''
    总结:
    1. 通常在输入验证码的时候,不区分大小写.可能就是将对应的字符串统一变成了大写或小写
    '''
  2. 判断区间内的首字母是否相同, startswith,endswith

print(a.startswith('r',0,len(a)))

# False

print(a.startswith('H',0,len(a)))

# True

print(a.endswith('e',0,len(a)))

# False

print(a.endswith('d',0,len(a)))

# True

'''
总结:
1. startswith,它可以判断区间内(顾头不顾尾)首字母是否为指定字符,返回bool值
2. endswith,它可以判断区间内(顾头不顾尾)尾字母是否为指定字符,返回bool值
'''
  1. 连接,join

    test_list = ["etc","plf","lt","xs","cd"]
    print("/".join(test_list)) # etc/plf/lt/xs/cd print('/'.join(a)) # h/e/l/l/o/ /w/o/r/l/d '''
    总结:
    1. 用来连接各个元素,一般用于路径的拼接
    '''
  2. 替换replace

    print(a.replace("o","P"))
    
    # HellP WPrld
    
    '''
    总结:
    1. 将字符串中的字符替换成指定字符
    '''
  3. 判断是否为数字isdigit

    print(a.isdigit())
    
    # False
    
    test_str = "123"
    print(test_str.isdigit()) # True '''
    总结:
    1. 判断字符串中是否全是数字
    2. 注意:
    当数字字符串中含有空格时,isdigit依然会返回True,因此我们使用数字时,一定要记得将空格替换掉!
    '''

了解

  1. 查找 find,rfind

    print(a.find("H"))
    
    # 0
    
    print(a.find("d"))
    
    # 10
    
    print(a.find("p"))
    
    # -1
    
    print(a.find("ell"))
    
    # 1
    
    '''
    总结:
    1. 当传入对应字符时,返回对应字符的下标.如果没有对应字符,则返回-1
    2. 当传入字符串时,返回对应字符串第一个字符的下标.如果没有,则返回-1
    '''
  2. index,rindex

    print(a.index("H"))
    
    # 0
    
    print(a.index("d"))
    
    # 10
    
    print(a.index("p"))
    
    # 抛异常,程序中断
    
    print(a.index("ell"))
    
    # 1
    
    '''
    总结:
    1. 当传入对应字符时,返回对应字符的下标.如果没有对应字符,则抛异常
    2. 当传入字符串时,返回对应字符串第一个字符的下标.如果没有,则抛异常
    3. 与find相比,find的方式更加友好
    '''
  3. count,字符串出现的次数

    print(a.count("o"))
    
    # 2
  4. center,ljust,rjust,zfill

    # center 居中
    print(a.center(30,"*")) # *********Hello World********** # ljust 居左
    print(a.ljust(30,"*")) # Hello World******************* # rjust 居右
    print(a.rjust(30,"*")) # *******************Hello World # zfill 默认以0填充
    print(a.zfill(30))
    # 0000000000000000000Hello World
  5. expandtabs, 设置制表符距离,默认为8

    print("aaa\tbbb".expandtabs())
    
    # aaa     bbb
    
    print("aaa\tbbb".expandtabs(4))
    
    # aaa bbb
  6. capitalize,swapcase,title

    print(a.capitalize())
    
    # Hello world
    
    print(a.swapcase())
    
    # hELLO wORLD
    
    a = "hello world"
    print(a.title())
    # Hello World

列表的内置方法

作用:多个装备、多个爱好、多门课程、甚至是多个女朋友

定义:[]内可以有多个任意类型的值,逗号分隔元素

plf = ["name","age","sex","tank"]
print(plf)

方法

append(元素) del 列表 my_list[下标]="修改内容" in/not in
extend(列表) pop() count(元素)
insert(位置,"元素") remove("元素") index("元素")
clear()

存一个值or多个值: 多个值

有序or无序: 有序

可变or不可变:可变

可变or不可变: 可变

  1. 追加 , append

    a = ["plf","lt","xs","cd"]
    a.append('www')
    print(a) # ['plf', 'lt', 'xs', 'cd', 'www']
  2. 增加列表

    a = ["plf","lt","xs","cd"]
    b = ["ls","ww","zhy"]
    a.extend(b)
    print(a) # ['plf', 'lt', 'xs', 'cd', 'ls', 'ww', 'zhy']
  3. 插入数据

    a = ["plf","lt","xs","cd"]
    a.insert(1,"www")
    print(a) # ['plf', 'www', 'lt', 'xs', 'cd']

  1. 删除列表

    a = ["plf","lt","xs","cd"]
    a.insert(1,"www")
    del a
    print(a) '''
    NameError Traceback (most recent call last)
    <ipython-input-16-71b7731a4ef0> in <module>
    2 a.insert(1,"www")
    3 del a
    ----> 4 print(a) NameError: name 'a' is not defined
    '''
  2. pop()

    a = ["plf","lt","xs","cd"]
    b = a.pop()
    print("a的值%s\n%s"%(a,b)) '''
    a的值:['plf', 'lt', 'xs']
    b的值:cd
    '''
  3. remove("元素")

    a = ["lt","plf","lt","xs","cd","cd"]
    a.remove("cd")
    a.remove("lt")
    print("a的值:%s"%(a)) '''
    a的值:['plf', 'lt', 'xs', 'cd']
    '''

  1. 根据下标更改

    a = ["lt","plf","lt","xs","cd","cd"]
    a[0] = "gunkai"
    print("a的值:%s"%(a)) '''
    a的值:['gunkai', 'plf', 'lt', 'xs', 'cd', 'cd']
    '''

  1. in/not in 是否在

    a = ["lt","plf","lt","xs","cd","cd"]
    print(bool("xxxx" in a))
    print(bool("xxxx" not in a)) '''
    False
    True
    '''
  2. count(元素),元素出现个数

    a = ["lt","plf","lt","xs","cd","cd"]
    print(a.count("lt")) '''
    2
    '''
  3. index("元素") ,索引

    a = ["lt","plf","lt","xs","cd","cd"]
    print(a.index("lt")) '''
    0
    '''

列表的函数

  1. len(),长度

    a = ["lt","plf","lt","xs","cd","cd"]
    print(len(a)) '''
    6
    '''
  2. max(list) ,返回列表元素最大值

    a = ["lt","plf","lt","xs","cd","cd"]
    b = ["plf","zj","xn","lt"]
    c = [1,200,3,4,5,6,7,8,9,100,111]
    print(max(a))
    print(max(b))
    print(max(c)) '''
    xs
    zj
    200
    ''' # min(list) 同理,返回列表元素最小值
  3. list(seq),强制类型转化

    a = "hello,world"
    b = (1,2,3,4,5,6)
    print(list(a))
    print(list(b)) '''
    ['h', 'e', 'l', 'l', 'o', ',', 'w', 'o', 'r', 'l', 'd']
    [1, 2, 3, 4, 5, 6]
    ''' '''
    总结:
    1. 可以强制类型转化 '''

其他

  1. clear,清除

    name_list = ['nick', 'jason', 'tank', 'sean']
    name_list.clear() print(f"name_list: {name_list}") '''
    name_list: []
    '''
  2. copy,拷贝/深拷贝

    name_list = ['nick', 'jason', 'tank', 'sean']
    
    print(f"name_list.copy(): {name_list.copy()}")
    
    '''
    name_list.copy(): ['nick', 'jason', 'tank', 'sean']
    ''' '''
    总结:
    1. 复制一个与原列表相同的列表 '''
  3. reverse, 反转

    name_list = ['nick', 'jason', 'tank', 'sean']
    name_list.reverse() print(f"name_list: {name_list}") '''
    name_list: ['sean', 'tank', 'jason', 'nick']
    ''' '''
    总结:
    1. 翻转排序 '''
  4. sort,排序

    a = [2113,3123,4,31,115,17,82,123,55,21]
    a.sort()
    print(a)
    a.sort(reverse=True)
    print(a)
    '''
    [4, 17, 21, 31, 55, 82, 115, 123, 2113, 3123]
    [3123, 2113, 123, 115, 82, 55, 31, 21, 17, 4]
    ''' ''' 总结:
    1. sort()排序后,没有返回值。因此不能这样打印:print(info.sort())
    2. sort()方法中,可以添加翻转等操作 '''

字典的内置方法

作用:当列表存很多元素时,列表会显示很乱,所有有了字典

定义方式:{} 内以逗号分隔开多个键值对 key:value的值,key一般为字符串,value可以为任意对象

a_dict = {
'name':'PLF',
'age':20,
'height':165,
'hobby_list':["ch","pd",'watch']
}

方法

info['键'] = 数据 del info["键"] = 要修改的元素 print(info["键"])
update() pop() print(info.get("不存在的键"))
fromkeys() popitem() for key,value in info.itmes()
setdefault() keys(),values(),items()

存一个值or多个值:多个值,且值为不可变类型

有序or无序:无序

  1. info['键'] = 数据

    a =  {"name":"plf","age":"20","sex":"nan"}
    a["address"] = "Chinese"
    print(a) '''
    {'name': 'plf', 'age': '20', 'sex': 'nan', 'address': 'Chinese'}
    '''
  2. update()

    a =  {"name":"plf","age":"20","sex":"nan"}
    b = {"address":"Chinese"}
    a.update(b)
    print(a) '''
    {'name': 'plf', 'age': '20', 'sex': 'nan', 'address': 'Chinese'} '''
  3. fromkeys()

    c_dic = dict.fromkeys(['name','age','sex'],None)
    print(c_dic) '''
    {'name': None, 'age': None, 'sex': None}
    '''
  4. setdefault()

    # dic之setdefault(),有指定key不会改变值;无指定key则改变值
    dic = {'a': 1, 'b': 2} print(f"dic.setdefault('a'): {dic.setdefault('a',3)}")
    print(f"dic: {dic}")
    print(f"dic.setdefault('c'): {dic.setdefault('c',3)}")
    print(f"dic: {dic}") '''
    dic.setdefault('a'): 1
    dic: {'a': 1, 'b': 2}
    dic.setdefault('c'): 3
    dic: {'a': 1, 'b': 2, 'c': 3}
    '''

  1. del

    dic = {'a': 1, 'b': 2}
    del dic['a'] print(dic) del dic
    print(dic) '''
    {'b': 2} ---------------------------------------------------------------------------
    NameError Traceback (most recent call last)
    <ipython-input-69-aded9265c051> in <module>
    4 print(dic)
    5 del dic
    ----> 6 print(dic) NameError: name 'dic' is not defined '''
  2. pop()

    # dic之删除pop()
    dic = {'a': 1, 'b': 2}
    dic.pop('a') # 指定元素删除 print(f"dic.pop('b'): {dic.pop('b')}")
    print(f"dic.get('a'): {dic.get('a')}") '''
    dic.pop('b'): 2
    dic.get('a'): None '''
  3. popitem()

    dic = {'a': 1, 'b': 2}
    
    print(f"dic.popitem(): {dic.popitem()}")   # 随机删除一个元素,无法指定
    
    '''
    dic.popitem(): ('b', 2) '''

  1. 根据key修改value

    a = {"name":"plf","age":"24","sex":"boy"}
    a["name"] = "cd"
    print(a) '''
    {'name': 'cd', 'age': '24', 'sex': 'boy'}
    '''

元组的内置方法

作用:类似于列表,只不过元祖只能取不能更改

定义方式:() 内用逗号隔开任意数据类型的元素

a = ("plf","lt","xs","cd")
print(a) '''
('plf', 'lt', 'xs', 'cd')
'''

方法:

索引取值 info["key"]
切片 info["key"]
长度 len(info)
成员运算 in 和 not in
循环
count
index

存储一个值 or 多个值:多个值

有序 or 无序:有序

可变 or 不可变:无


集合类型内置方法

  1. 作用:存多个值,为了集合之间做运算

  2. 定义方式:

    s = set()
    s = {1,2,3,4,5,1}
  3. 方法

    1. 优先掌握

      • 去重

        a = [5, 2, 5, 1, 4, 3, 4,1,0,2,3,8,9,9,9]
        print(list(set(a))) #将去掉重复的项后,再重新转成list '''
        [0, 1, 2, 3, 4, 5, 8, 9] '''
      • 并集

        a = {1,2,3}
        b = {2,3,4}
        c = a|b
        print(c) '''
        {1, 2, 3, 4}
        '''
      • 交集

        a = {1,2,3}
        b = {2,3,4}
        c = a&b
        print(c) '''
        {2, 3}
        '''
      • 差集

        a = {1,2,3}
        b = {2,3,4}
        print(a-b)
        print(b-a) '''
        {1}
        {4}
        '''
      • 对称差集

        a = {1,2,3}
        b = {2,3,4}
        print(a^b) '''
        {1, 4}
        '''
      • 父集 ( 判断 )

        a = {1,2,3}
        b = {2,3,4}
        print(a > b)
        a = {1,2,3,4}
        print(a > b) '''
        False
        True
        '''
      • 子集

        a = {1,2,3}
        b = {2,3,4}
        print(a < b)
        a = {2,3}
        print(a < b) '''
        False
        True
        '''
      • ==

        a = {1,2,3,4}
        b = {1,2,3,4}
        print(a == b) a = {1,2,3}
        print(a == b) '''
        True
        False
        '''
    2. 需要掌握

      • add 添加元素

        s = {1, 2, 'a'}
        s.add(3) print(s) '''
        {1, 2, 3, 'a'} '''
      • difference_update 去除原集合中重复的元素

        pythoners = {'jason', 'nick', 'tank', 'sean'}
        linuxers = {'nick', 'egon', 'kevin'}
        pythoners.difference_update(linuxers) print(f"pythoners.difference_update(linuxers): {pythoners}") '''
        pythoners.difference_update(linuxers): {'jason', 'sean', 'tank'}
        '''
      • isdisjoint 集合没有共同的部分返回True,否则返回False

        pythoners = {'jason', 'nick', 'tank', 'sean'}
        linuxers = {'nick', 'egon', 'kevin'}
        pythoners.isdisjoint(linuxers) print(f"pythoners.isdisjoint(linuxers): {pythoners.isdisjoint(linuxers)}") '''
        pythoners.isdisjoint(linuxers): False
        '''
      • remove 值不存在会报错

        b = {1,2,3,4}
        b.remove(4)
        print(b) b.remove(5)
        print(b) '''
        {1, 2, 3} KeyError Traceback (most recent call last)
        <ipython-input-84-af6d44ebcdf4> in <module>
        1 a = {1,2,3}
        2 b = {1,2,3,4}
        ----> 3 b.remove(5)
        4 print(b) KeyError: 5 '''
      • discard # 不会报错

        s = {1, 2, 'a'}
        # s.remove(3) # 报错
        s.discard(3) print(s) '''
        {1, 2, 'a'} '''
  4. 多个值 or 一个值:多个值

  5. 有序 or 无序:无序

  6. 可变 or 不可变:可变


布尔类型

作用:一般用于判断,除了0/None/空/False自带布尔值为False,其他的数据类型自带布尔值为True


数据类型总结

定律:

id不变,值变,为可变类型。 id变,值变,为不可变类型

一个值 多个值
整型/浮点型/字符串 列表/元组/字典/集合
有序 无序
字符串/列表/元组 集合/字典
可变 不可变
列表/字典/集合 整型/浮点型/字符串