• 可变不可变类型,数字类型及其常用操作,字符串类型及其常用操作


    一、可变不可变类型

    1、可变类型:值改变,但是id不变,证明就是在改变原值,是可变类型
    2、不可变类型:值改变,id也变,证明是产生了新值,并没有改变原值,原值是不可变类型
    #数字
    x = 123
    print(id(x))#8791380317664
    x = 456
    print(id(x))#31218128
    
    #列表
    l1=[111,222,333]
    print(id(l1))#31582720
    l1[0] = 1111111111111111
    print(l1)#[1111111111111111, 222, 333]
    print(id(l1))#31582720
    ps:python是一门解释型 强类型 动态语言

    二、数字类型及其常用操作

    整型int
      1、用途:年龄、个数、号码、出生年等
      2、定义方式
      age = 18 # age = int(18)
      # int功能可以把纯整数数字的字符串转换成int类型,float不行,会直接报错。
    res = int("18")#<class 'int'>
    # res = int("1.8")#float类型会报错
    print(type(res))
      了解(***)
    #进制转换
    print(bin(11))  # 0b1011
    print(oct(11))  # 0o13
    print(hex(11))  # 0xb
      3、常用操作+内置的方法
        算数运算符与比较运算
    浮点型float
      1、用途:薪资、身高、体重等
      2、定义方式
      salary = 3.1 # salary = float(3.1)
      # float功能可以把浮点数组成的字符串转换成float类型
    res = float("1.8")
    print(type(res))#<class 'float'>
      3、常用操作+内置的方法
        算数运算符与比较运算
    总结:
      数字类型都是只能存一个值,是不可变类型
      无常用操作,无内置的方法

    三、字符串类型及其常用操作

    1、用途:记录描述性质的状态,例如名字、性别、国籍等
    2、定义方式:在引号('',"",'''''',""""""")内包含一串字符串
    # str功能可以把任意类型转换成str类型
    res=str([1,2,3])  
    print(res,type(res))# "[1,2,3]" <class 'str'>
    3、常用操作+内置的方法
    =========优先掌握的操作=========
    1、按索引取值(正向取+反向取) :只能取
    s = "hello world"
    print(s[0],type(s[0]))  # "h" <class 'str'>
    print(s[-1])#'d'
    
    # s[1] = "E"  # 报错,不能修改
    # s[2222]# 非法操作
    # s[11] = "A" #超出索引,#非法操作
    2、切片(顾头不顾尾,步长)=>属于拷贝操作
    #可以省略步长,默认为1
    #可以省略起始位置与步长,默认起始位置为0 步长为1
    s = "hello world"
    # new_s=s[1:7]
    # print(new_s)
    # print(s)
    
    # new_s=s[1:7:2]  #1 3 5
    # print(new_s)
    # print(s)
    
    # new_s=s[:7:2]
    # new_s=s[::2]  # 0 2 4 6 8 10
    #               h l o w r  d
    # print(new_s)
    
    # new_s=s[::]  # 完整拷贝字符串,只留一个冒号就可以new_s=s[:]
    # print(new_s)
    3、长度len
    s = "hello world"
    print(len(s))
    
    res=print("sfd")
    print(res)
    4、成员运算in和not in
    s = "hello world"
    print("hel" in s)
    print("egon" not in s) # 语义明确,推荐使用
    # print(not "egon" in s)
    5、移除左右两边空白(
     	也算空白)strip   移除左右两边特定的字符,空白也是字符
    s = " 
            hel lo  	 "
    new_s = s.strip()
    print(new_s)
    print(s)  # 没有改变原字符串
    # 应用案列:
    # name = input("your name>>> ").strip()  # name = "egon "
    # pwd = input("your pwd>>> ").strip()
    去除左右两边的非空白字符strip
    print("**+=-%^#*$^&@!***he**llo**%^#**+=**".strip("*+=-%^$^@!&#"))
    6、切分split:把字符串按照某个分隔符切成一个列表
    userinfo = "egon_dsb:123:18:3.1"
    res = userinfo.split(":")
    print(res)#['egon_dsb', '123', '18', '3.1'] 注意得到的是列表
    print(res[0])#egon_dsb
    # 纯字符串组成的列表
    l = ["aaaa", "bbb", "ccc"]
    # res=l[0]+":"+l[1]+":"+l[2]#原始方式,利用字符串相加
    res = ":".join(l) #join方式
    print(res, type(res))  #aaaa:bbb:ccc <class 'str'>
    7、join   连接的元素必须是字符串
    userinfo = "egon_dsb:123:18:3.1"#字符串
    print("-".join(userinfo))#e-g-o-n-_-d-s-b-:-1-2-3-:-1-8-:-3-.-1
    
    userinfo = "egon_dsb:123:18:3.1"
    res = userinfo.split(":")#得到列表['egon_dsb', '123', '18', '3.1']
    print("-".join(res)) #egon_dsb-123-18-3.1
    7、循环
    for i in "hello":
        print(i)
    ==========需要掌握的操作=========
    1、strip,lstrip,rstrip    
    print("***hello***".strip("*"))
    print("***hello***".lstrip("*"))
    print("***hello***".rstrip("*"))
    2、lower,upper
    msg = "AbCDEFGhigklmn"
    res1 = msg.lower()
    res2 = msg.upper()
    print(res1)
    print(res2)

    3、swapcase大小写反转

    msg = "AbCDEFGhigklmn"
    res3=msg.swapcase()
    print(res3)
    4、startswith,endswith
    msg = "sb is lxx sb"
    print(msg.startswith("sb"))#True
    print(msg.endswith("b"))#True
    print(msg.endswith("c"))#False
    5、split,rsplit
    userinfo="egon:123:18"
    print(userinfo.split(":"))#['egon', '123', '18']
    print(userinfo.split(":",1))#['egon', '123:18']
    print(userinfo.rsplit(":",1))#['egon:123', '18']
    6、replace  replace('原值','现值')   
    msg = "***egon hello***"
    res=msg.replace('*','').replace(' ','')
    res1=msg.strip('*').replace(' ','')
    print(res)
    print(res1)
    print(msg)#不变

    7、format的三种玩法

    (1)%s的方式

    (2)format的方式

    (3)f''  (不要乱用python3.6开始才有此功能)

    #(1)%s的方式
    name = "egon"
    age = 18
    res1="my name is %s my age is %s" % (name,age)
    print(res1)
    #(2)format的方式
    name = "egon"
    age = 18
    res1="my name is {} my age is {}".format(name,age)
    res2="{0}{0}{0}{1}".format(name,age)#egonegonegon18
    res3="my name is {name} my age is {age}".format(age=18,name="egon")
    print(res1)
    print(res2)
    print(res3)
    #(3)f''
    name = "egon"
    age = 18
    res1 = f'my name is {name} my age is {age}'
    print(res1)
    了解:f搭配{}可以执行字符串中的代码
    res=f'{len("hello")}'
    print(res)
    
    f'{print("hello")}'
      f包含的字符串可以放到多行
    name = "egon"
    age = 18
    res1 = f"my name is {name} " 
           f"my age is {age}"
    print(res1)
    # {}内不能有以及#   外层{}有取消掉内层{}的意思
    print(f'my name is {{egon}}')#{}类似于
    
    print('胜率是 %s%%' %70)
    8、isdigit:判断字符串是否由纯数字组成,只能判断整形
    print("adsf123".isdigit())#False
    print("123".isdigit())#True
    print("12.3".isdigit())#False
    age = input('>>>: ') # age = "        18     "
    if age.isdigit():#可先判断是否为数字,减少程序bug
        age=int(age)
        if age > 18:
            print('猜大了')
        elif age < 18:
            print('猜小了')
        else:
            print('猜对了')
    else:
        print('必须输入数字,小垃圾')
    ==========需要了解的操作=========
    1、find,rfind,index,rindex,count
    总结:find 查找找到所要查找的位置的索引值,结果为-1代表没找到;
       rfind从右往左开始查找找到所要查找的索引的位置
       index查找找到所要查找的位置的索引值,找不到报错
       rindex从右往左查找,找不到报错
       count计数
    x = "hello egon egon egon"
    # res=x.find("egon") #代表从索引6开始
    # res=x.find("egon123") # -1代表没有找到
    # print(res)
    
    res=x.rfind("egon")
    print(res)
    res=x.find("egon",0,3)#从索引0 到3里查找
    print(res)
    
    #index
    # res = x.index("egon123") # 找不到则报错
    res = x.index("egon") # 代表从索引6开始
    print(res)
    
    #count
    a = "hello,world!"
    d = {}
    for i in a:
        d[i] = a.count(i)
    print (d)#{'h': 1, 'e': 1, 'l': 3, 'o': 2, ',': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1}

    2、center,ljust,rjust,zfill

        总结:center居中;

        ljust居左;

        rjust居右;

        zfill居右,用0补全,默认右对齐

    x = "egon"
    
    print(x.center(50,'*'))#居中,共50的字符,除了x外其余用*填满
    print(x.ljust(50,"*"))#居右,共50的字符,除了x外其余用*填满
    print(x.rjust(50,"*"))#居左,共50的字符,除了x外其余用*填满
    print(x.zfill(50))#居右,共50的字符,除了x外其余默认用0填满
    print(x.rjust(50,"0"))#居右,共50的字符,除了x外其余用0填满

    3、expandtabs展开选项卡----指定 制表符的长度

    expandtabs() 方法把字符串中的 tab 符号(' ')转为空格,tab 符号(' ')默认的空格数是 8。

    从头开始数,数到第一个 正好为8个空格,不足则补空格,如果还有 ,接着从第一个 数到第二个 仍然为8个空格,以此类推直到最后一个 结束。

    print("hello	world".expandtabs(1)) #hello world 长度为11
    print("hello	world".expandtabs(2)) #hello world长度为11
    print("hello	world".expandtabs(3)) #hello world长度为11
    print("hello	world".expandtabs(4)) #hello world长度为13
    print("hello	world".expandtabs(5)) #hello world长度为15
    print("hello	world".expandtabs(6)) #hello world长度为11
    4、captalize,swapcase,title
    总结:captalize首字母大写
       swapcase大小写翻转
       title每个单词首字母大写 利用IDE开发工具,自动提示的功能
    print("hello world egon".capitalize())#首字母大写
    print("aBcDeF".swapcase())#大小写翻转
    print("hello world egon".title())#每个单词首字母大写

    5、is其他

    name='egon123'
    print(name.isalnum()) #字符串由字母或数字组成
    print(name.isalpha()) #字符串只由字母组成
    
    name="aaainputbbbbb"
    print(name.isidentifier())#
    
    name="abc123"
    print(name.islower())#是否都是大写
    print(name.isupper())#是否都是小写
    
    name="     "
    print(name.isspace())#字符串是否为空
    
    name="My Name Is Egon"
    print(name.istitle())#字符串每个单词首字母为大写

    6、is数字系列

    #在python3中
    num1=b'4' #bytes
    num2=u'4' #unicode,python3中无需加u就是unicode
    num3='四' #中文数字
    num4='Ⅳ' #罗马数字
    #1、 bytes、unicode
    # print(num1.isdigit())
    # print(num2.isdigit())
    # print(num3.isdigit())
    # print(num4.isdigit())
    
    
    # 2、unicode、中文数字、罗马数字
    # print(num2.isnumeric())
    # print(num3.isnumeric())
    # print(num4.isnumeric())
    
    # 3、unicode
    # print(num2.isdecimal())
    # print(num3.isdecimal())
    # print(num4.isdecimal())

    str类型总结:

    存一个值,有序,不可变

  • 相关阅读:
    又见回文 字符串
    学密码学一定得学程序 KMP
    学密码学一定得学程序 KMP
    KMP简单应用
    KMP简单应用
    用ALAssetsLibrary将过滤后图片写入照片库
    iOS 8版本信息与屏幕尺寸
    屏幕适配的那些坑
    从工程中删除Cocoapods
    AVCaptureSession 照相时获取 AVCaptureVideoPreviewLayer尺寸
  • 原文地址:https://www.cnblogs.com/guojieying/p/13279970.html
Copyright © 2020-2023  润新知