python之字符串,列表,字典内置方法总结

Posted plf-jack

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之字符串,列表,字典内置方法总结相关的知识,希望对你有一定的参考价值。

数字类型的内置方法

整型/浮点型

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

字符串类型的内置方法

掌握 熟悉 了解
按索引取值 ,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

列表的内置方法

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

==增==

  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. 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']
    '''
  3. reverse, 反转

    name_list = ['nick', 'jason', 'tank', 'sean']
    name_list.reverse()
    
    print(f"name_list: {name_list}")
    
    
    '''
    name_list: ['sean', 'tank', 'jason', 'nick']
    '''
  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]
    '''

字典的内置方法

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

==增==

  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. popitems()

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

以上是关于python之字符串,列表,字典内置方法总结的主要内容,如果未能解决你的问题,请参考以下文章

Python基础之公共方法

python常用操作之使用多个界定符(分隔符)分割字符串

python常用操作之使用多个界定符(分隔符)分割字符串

数据类型内置方法

python数据类型之内置方法

python基础---整型字符串列表元组字典内置方法和文件操作介绍