Python-数字&字符串&列表及其内置方法

1、int & float数字类型

1、用途+定义方式
    #整型int
      作用:年纪,等级,身份证号,qq号等整型数字相关
      定义:age=10  # 本质age=int(10)
    #浮点型float
      作用:薪资,身高,体重,体质参数等浮点数相关
        定义:salary=3000.3  # 本质salary=float(3000.3)
    
2、二进制,八进制,十进制,十六进制 
    二进制转换函数 bin()
    八进制转换函数 oct()
    十进制转换函数 int()
    十六进制转换函数 hex()
    # 使用示例
    >>> x = 10
    >>> print(bin(x))
    0b1010
    >>> print(oct(x))
    0o12
    >>> print(int(x))
    10
    >>> print(hex(x))
    0xa
    >>>

3、常用操作+内置的方法
    就是 + - * ** / // % == > >= < <= != += -= 等等
    
#===========该类型总结===========
存一个值    
没有有序or无序的概念
不可变

2、字符串

数据类型转换:
    res = str(1111)  # 可以把所有类型转换成字符串类型
    print(res, type(res))
    
#===========该类型总结===========
存一个值    
有序
不可变

2.1、优先掌握的内置方法

# 要搞清楚哪些有返回值,哪些没有,还有每个内置方法的参数
1、按索引取值(正向取+反向取) :只能取
	# 示例1:按照索引取值(正向取+反向取),只能取不能存,因为是不可变类型
    word = 'hello world'
    print(word[2])  # 输出结果 l,按照索引取值
    word[2] = 'p'  # 报错,str类型不可变
    
2、切片(顾头不顾尾,步长)
    # 示例2:切片(顾头不顾尾,步长)
    word = 'hello world'
    print(word[:3])  # 输出结果 hel,顾头不顾尾
    print(word[1:8:2])  # 输出结果 el o,步长为2
    print(word[::-1])  # 输出结果 dlrow olleh,反向取
    
3、长度 len()
	# 示例3:长度len()
    word = 'hello world'
    print(len(word))  # 输出结果 11
    
4、成员运算 innot in
    # 示例4:成员运算 in & not in
    word = 'hello world'
    print('j' in word)  # 输出结果 False
    print('j' not in word)  # 输出结果 True
    print('hel' in word)  # 输出结果 True
    print('rld' not in word)  # 输出结果 False
    
5、移除空白strip
    # 示例5:移除空白strip()
    name = '   zxl  ** # '
    print(name.strip())  # 输出结果 zxl  ** #,默认会移除两边的空格
    print(name.strip(' #*'))  # 输出结果 zxl,str.strip('需要移除的参数')
    
6、切分split
    # 示例6:切分split(),按照参数字符(默认以空格为分隔符)切分成列表类型,可指定切分次数
    file = 'root:x:0:0:/home/root:/bin/bash'
    print(file.split(':'))  # 输出结果 ['root', 'x', '0', '0', '/home/root', '/bin/bash']
    print(file.split(':', 1))  # 输出结果 ['root', 'x:0:0:/home/root:/bin/bash']
    aaa = '11 22 33 44'
    print(aaa.split())  # 输出结果 ['11', '22', '33', '44']

7、循环
    # 示例7:循环for
    aaa = 'hello'
    for i in aaa:
        print(i)  # 输出结果 h\ne\nl\nl\no\n

2.2、需要掌握的内置方法

# 要搞清楚哪些有返回值,哪些没有,还有每个内置方法的参数
1、strip,lstrip,rstrip
2、lower,upper
3、startswith,endswith
4format的三种玩法
5、split,rsplit
6、join
7、replace
8、isdigit
1、strip,lstrip,rstrip
    # 移除空白,左移除,右移除
    name = '***zxl***'
    print(name.strip('*'))  # 输出结果 zxl
    print(name.lstrip('*'))  # 输出结果 zxl***
    print(name.rstrip('*'))  # 输出结果 ***zxl
2、lower,upper
    # 全小写,全大写
    aaa = 'HeLlo'
    print(aaa.lower())  # 输出结果 hello
    print(aaa.upper())  # 输出结果 HELLO
3、startswith,endswith
    # 判断开头,判断结尾
    aaa = 'hello worldzxl'
    print(aaa.startswith('he'))  # 输出结果 True
    print(aaa.startswith('zxl', 11, 200))  # 输出结果 True
    print(aaa.startswith('hee'))  # 输出结果 False
    print(aaa.endswith('d'))  # 输出结果 True
    print(aaa.endswith('dd'))  # 输出结果 False
4format的三种玩法
# format格式化输出
4.1) 自定义关键字匹配
    res = 'my name is {name},my age is {age}'.format(age=18, name='zxl')
    print(res)  # 输出结果 my name is zxl,my age is 18

4.2) 按照索引匹配(默认和%s占位符一样,一一对应)
    res1 = 'my name is {},my age is {}'.format(18, 'zxl')
    print(res1)  # 输出结果 my name is 18,my age is zxl
    res2 = 'my name is {1},my age is {0}'.format(18, 'zxl')
    print(res2)  # 输出结果 my name is zxl,my age is 18
    res3 = 'my name is {1}{1}{1},my age is {0}{1}'.format(18, 'zxl')
    print(res3)  # 输出结果 my name is zxlzxlzxl,my age is 18zxl

4.3) format高级玩法,对齐填充(<左对齐,>右对齐,^居中)
    res1 = "my name is {1:*<10} my age is {0}".format(18,"zxl")
    res2 = "my name is {1:*>10} my age is {0}".format(18,"zxl")
    res3 = "my name is {1:*^10} my age is {0:=^10}".format(18,"zxl")
    print(res1)  # 输出结果 my name is zxl*******,my age is 18
    print(res2)  # 输出结果 my name is *******zxl,my age is 18
    print(res3)  # 输出结果 my name is ***zxl****,my age is ====18====

4.4) 进制与精度
    res1 = "my name is {1:=^10} my age is {0:b}".format(18,"zxl")  # b二进制
    res2 = "my name is {1:=^10} my age is {0:o}".format(18,"zxl")  # o八进制
    res3 = "my name is {1:=^10} my age is {0:x}".format(18,"zxl")  # x十六进制
    res4 = "my name is {1:=^10} my salary is {0:,}".format(13333333333338,"zxl")
    res5 = "my name is {1:=^10} my age is {0:.3f}".format(3.7777,"zxl")  # 会四舍五入
    print(res1)  # 输出结果 my name is ===zxl====,my age is 10010
    print(res2)  # 输出结果 my name is ===zxl====,my age is 22
    print(res3)  # 输出结果 my name is ===zxl====,my age is 12
    print(res4)  # 输出结果 my name is ===zxl====,my salary is 13,333,333,333,338
    print(res5)  # 输出结果 my name is ===zxl====,my age is 3.778

4.5) *传入列表值,**传入字典的key和value
    l1 = [18, 'zxl', 'male']  # 还是按照索引传值的,要保证列表有足够的值,否则报错
    res1 = 'my name is {},my age is {}'.format(*l1)
    print(res1)  # 输出结果 my name is 18,my age is zxl
    res2 = 'my name is {1},my age is {0}'.format(*l1)
    print(res2)  # 输出结果 my name is zxl,my age is 18

    d1 = {'name':'zxl', 'age':18, 'gender':'male'}  # 按照key位置传值
    res1 = 'my name is {name},my age is {age}'.format(**d1)
    print(res1)  # 输出结果 my name is zxl,my age is 18
    res2 = 'my name is {gender},my age is {age}'.format(**d1)
    print(res2)  # 输出结果 my name is male,my age is 18

    # 错误使用示范
    info={"age":18,"name":"egon"}
    res="my name is {} my age is {}".format(*info)  # 一个*,则只能传入key
    print(res)  # 输出结果 my name is age,my age is name

4.6) f""
    name = "zxl"
    age = 18
    res = f"my name is {name},my age is {age}"
    print(res)  # 输出结果 my name is zxl,my age is 18
5、split,rsplit
    # 切分,右切分
    info = "root:123:0:0"
    print(info.split(':'))  # 输出结果 ['root', '123', '0', '0']
    print(info.split(":", 2))  # 输出结果 ['root', '123', '0:0']
    print(info.rsplit(":", 2))  # 输出结果 ['root:123', '0', '0']
6、join
    # 和split相反
    # 用一个字符把一个列表连接成字符串,列表内包含的元素必须是字符串类型
    l1 = ["a", "b", "c"]
    # print(l[0] + ":" + l[1] + ":" + l[2])
    res = ":".join(l1)
    print(res)  # 输出结果 a:b:c

    a = 'hello'
    print(':'.join(a))  # 输出结果 h:e:l:l:o
7、replace
    # 用新的字符替换源字符
    msg="egon is hahah egon"
    res=msg.replace("egon","EGON")
    print(res)  # 输出结果 EGON is hahah EGON
8、isdigit
    # 判断是否纯数字
    print("abc".isdigit())  # 输出结果 False
    print("123  ".isdigit())  # 输出结果 False
    print("12.3".isdigit())  # 输出结果 False
    print("123".isdigit())  # 输出结果 True

    # 拓展
    is数字系列
    num1 = b'4'  # bytes
    num2 = u'4'  # unicode,python3中无需加u就是unicode
    num3 = '四'  # 中文数字
    num4 = 'Ⅳ'  # 罗马数字

    #  bytes,unicode
    print(num1.isdigit())  # 输出结果 True
    print(num2.isdigit())  # 输出结果 True
    print(num3.isdigit())  # 输出结果 False
    print(num4.isdigit())  # 输出结果 False

    # unicode,中文、罗马
    num1没有该方法
    print(num2.isnumeric())  # 输出结果 True
    print(num3.isnumeric())  # 输出结果 True
    print(num4.isnumeric())  # 输出结果 True

    # unicode
    num1没有该方法
    print(num2.isdecimal())  # 输出结果 True
    print(num3.isdecimal())  # 输出结果 False
    print(num4.isdecimal())  # 输出结果 False

2.3、其他方法(了解即可)

1、find,rfind,index,rindex,count
    # 示例1:find,rfind,index,rindex,count
    msg = "xxhegonllegon123abclxxx"
    print(msg.find("egon"))  # 3,找到则返回索引,不会继续下去了
    print(msg.find("egonx"))  # -1,找不到返回-1
    print(msg.find("egon", 6, 20))  # 9,在指定索引范围内查找
    print(msg.find("egon", 6, 7))  # -1
    print(msg.rfind("egon"))  # 9
    print(msg.find("egonx"))  # -1
    print(msg.index("egonx"))  # 直接报错,index找不到会直接报错,尽量少用
    print(msg.rfind("egon"))  # 9
    print(msg.rindex("egon"))  # 9
    print(msg.count('egon'))  # 2,找到会返回个数值
    print(msg.count('egonx'))  # 0,找不到返回0
    
2、center,ljust,rjust,zfill
    # 示例2:center,ljust,rjust,zfill
    print("egon".center(10, "*"))  # ***egon***
    print("egon".ljust(10, "*"))  # egon******
    print("egon".rjust(10, "*"))  # ******egon
    print("egon".zfill(10))  # 000000egon,用0填充,默认右对齐

3、expandtabs
    # 示例3:expandtabs
    name='egon\thello'  # \t,制表符tab,默认4个空格数
    print(name)  # egon    hello
    print(name.expandtabs(1))  # egon hello
    
4、captalize,swapcase,title
    # 示例4:captalize,swapcase,title
    print("hello world".capitalize())  # Hello world,句首字母大写
    print("hello world".title())  # Hello World,每个单词首字母大写
    print("HeL".swapcase())  # hEl,大小写反转
    
5is数字系列
    # 示例5:is数字系列
    isdigit(bytes,unicode)  # bytes,unicode为True,其他类型数字结果为False
    isnumeric(unicode,中文数字,罗马数字)  # 不支持bytes类型数字,其他三种都为True
    isdecimal(unicode)  # 不支持bytes类型数字,unicode结果为True,其他两种都为False
    
6is其他
    # 示例6:is其他系列
    isalnum	判断字符串是否只有字母或数字组成
    isalpha	判断字符串是否只有纯字母组成
    isidentifier	判断字符串是否是python关键字或合规的变量名
    islower	判断字符串是否全小写
    isupper	判断字符串是否全大写
    isspace	判断字符串是否全为空格
    istitle	判断字符串是否每个单词首字母大写

    name = 'egon123'
    print(name.isalnum())  # True
    print(name.isalpha())  # False

    name = "def"
    print(name.isidentifier())  # True

    name = "xxx"
    print(name.islower())  # True
    print(name.isupper())  # False

    name = "  1 "
    print(name.isspace())  # False

    name = "Hello World"
    print(name.istitle())  # True

3、列表类型的内置方法

数据类型转换:
print(list('hello'))  # ['h','e','l','l',o]
print(list({'k1':111,'k2':222}))  # ['k1','k2']
print(list(range(5)))  # [0,1,2,3,4]

#===========该类型总结===========
存多个值    
有序
可变

3.1、列表优先掌握的内置方法

1、按索引存取值(正向存取+反向存取):即可改也可以取
    # 示例1:
    l = ['aaa',222,'ccc']
    print(l[0])  # 'aaa'
    print(l[-1])  # 'ccc'
    l[0] = 'xxx'
    print(l)  # ['xxx',222,'ccc']
    l[3] = 'ddd'  # 报错,因为索引不存在
2、切片(顾头不顾尾,步长)
    # 示例2:
    l = [111, 222, 333, 444, 555, 666, 777]
    print(l[0:5])  # [111,222,333,444,555]
    print(l[0:5:2])  # [111,333,555]
    print(l[:])  # [111,222,333,444,555,666,777],拷贝新列表
    print(l[::-1])  # [777,666,555,444,333,222,111],列表反转
3、长度 len()
    # 示例3:
    l = [111, 222, 333, 444, 555, 666, 777]
    print(len(l))  # 7
4、成员运算 innot in
    # 示例4:
    l = [111, 222, 333, 444, 555, 666, 777]
    print(111 in l)  # True
5、追加元素 l.append,加在最后;插入元素 l.insert,加在指定索引前
    # 示例5:
    l=["aaa",2222,"cccc"]
    res1 = l.append('ddd')  
    print(res1)  # None,没有返回值
    print(l)  # ['aaa',2222,'cccc','ddd']
    print(l.append(111))  # ['aaa',2222,'cccc','ddd',111]

    # 示例6:
    l=["aaa",2222,"cccc"]
    res2 = l.insert(1,'xxx')
    print(res2)  # None,没有返回值
    print(l)  # ['aaa','xxx',2222,'cccc']
    print(l.insert(0,111))  # [111,'aaa','xxx',2222,'cccc']
6、删除
6.1) 万能删除 del
    l=["aaa",2222,"cccc"]
    del l[0]
    print(l)  # [2222,'cccc']

6.2) l.remove,指定元素删除
    l=["aaa",2222,"cccc"]
    res = l.remove(2222)
    print(res)  # None
    print(l)  # ['aaa','cccc']

6.3) l.pop,指定索引删除,默认删除最后一个,会有返回值,返回删除的元素
    l=["aaa",2222,"cccc"]
    res = l.pop()
    print(res)  # 'cccc'
    print(l)  # ['aaa',2222]
    print(l.pop(0))  # [2222]
7、循环
    # 示例7:
    l=[111,222,333,444,555,666,777]
    for i in l:
        print(i)

3.2、列表需要掌握的内置方法

1、l.count,统计某个元素出现的个数
    # 示例1:
    l = [111, 222, 333, 111, 444, 555, 666, 777]
    print(l.count(111))  # 2

2、l.extend,可以一次追加多个值,需要是可迭代对象
    # 示例2:
    l = [111, 222, 333]
    print(l.extend('hello'))  # [111,222,333,'h','e','l','l','o']
    print(l.extend(['xxx','yyy']))  # [111,222,333,'h','e','l','l','o','xxx','yyy']

3、l.reverse,列表反转,和 l[::-1]的结果一样
    # 示例3:
    l=[111,222,333,111,444,555,666,777]
    res=l.reverse()
    print(l)  # [777, 666, 555, 444, 111, 333, 222, 111]
    print(res)  # None

4、l.index,查看某元素的索引位置,可指定查找范围(范围顾头不顾尾)
    # 示例4:
    l = [111, 222, 333, 111, 444, 555, 666, 777]
    print(l.index(111,1,5))  # 3
    print(l.index("xxx",1,5))  # 报错,因为没有要查找的元素值

5、l.clear,清空列表
    # 示例5:
    l = [111, 222, 333, 111, 444, 555, 666, 777]
    l.clear()
    print(l)  # [],列表被清空

6、l.sort,参数reverse=True表示降序排列,不写或者reverse=False表示升序排列;参数key= 要配合函数使用
    # 示例6:
    l=[3,-1,4,9,7,]  
    l.sort(reverse=True)
    print(l)  # [9,7,4,3,-1]
    l=l=[3,-1,4,9,7,'xxx']  # 要求列表中的元素值之间能够相互比较
    print(l.sort())  # 报错

    # 示例7:参数key=的案例
    有如下列表,请按照年龄排序(涉及到匿名函数)
    l=[
        {'name':'alex','age':84},
        {'name':'oldboy','age':73},
        {'name':'egon','age':18},
    ]
    l.sort(key=lambda item:item['age'])
    print(l)  # [{'name':'egon','age':18}, {'name':'oldboy','age':73}, {'name':'alex','age':84}]

7、l.copy,和 l[:] 都是属于浅copy。这种copy对于可变类型来说,只是简单的copy了一下外层的内存地址,对于可变类型内部的元素进行修改的话,copy的数据也会受到影响,而深copy不会。

4、补充:深浅copy

4.1、浅copy示意图

l1 = ['str', 123, [111, 222]]
l2 = l1.copy()  
print(l2)
或者 
l2 = l1[:]
print(l2)

print(id(l1[0]),id(l1[1]),id(l1[2]))
# 2202582975920 2202583062928 2202582998400
print(id(l2[0]),id(l2[1]),id(l2[2]))
# 2202582975920 2202583062928 2202582998400

在这里插入图片描述

4.2、深copy示意图

from copy import deepcopy
l1 = ['str', 123, [111, 222]]
l2 = deepcopy(l1)

print(id(l1[0]),id(l1[1]),id(l1[2]))
# 2295281551408 2295281637776 2295281860480
print(id(l2[0]),id(l2[1]),id(l2[2]))
# 2295281551408 2295281637776 2295282063552

在这里插入图片描述

5、模拟数据结构:队列,堆栈

5.1、队列:FIFO先进先出

l1 = []
# 入队
l1.append('first')
l1.append('second')
l1.append('third')
print(l1)  # ['first', 'second', 'third']
# 出队
print(l1.pop(0))
print(l1.pop(0))
print(l1.pop(0))

5.2、堆栈:LIFO后进先出

l1 = []
# 入栈
l1.append('first')
l1.append('second')
l1.append('third')
print(l1)  # ['first', 'second', 'third']
# 出栈
print(l1.pop())
print(l1.pop())
print(l1.pop())
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值