zoukankan      html  css  js  c++  java
  • python入门day07——可变不可变类型、数字类型、字符串类型.md

    一、可变不可变类型

    1、可变类型

            值改变,但id不变,证明就是在改变原值,是可变类型

    l1 = [111, 222, 333]
    print(id(l1))  # 140685250975616
    l1[0] = 112233
    print(l1)  # [112233, 222, 333]
    print(id(l1))  # 140685250975616
    

    2、不可变类型

            值改变,id也变,证明是产生了新值,压根没有改变原值,证明原值是不可以被修改的

    x = 123
    print(id(x))  # 4327958992
    x = 456
    print(id(x))  # 140669456569680
    

    二、数字类型

    1、整型

            1、用途:年龄、个数、号码、出生年等
           2、定义方式:age = 18 # age = int(18)
           int功能可以把纯数字的字符串转换成int类型(小数点也不行)

    # 进制转换 了解(***)
    print(bin(11))  # 0b1011 十进制转二进制
    print(oct(11))  # 0o13  十进制转八进制
    print(hex(11))  # 0xb  十进制转十六进制
    

            该类型只能存一个值、是不可变类型

    2、浮点型

            1、用途:薪资、身高、体重
            2、定义方式:x = 3.1 # x = float(3.1)
            float功能可以把浮点数组成的字符串转换成float类型
            该类型只能存一个值、是不可变类型

    3、长整形(了解)

            在python2中(python3中没有长整形的概念):

    >>> x = 12312321321111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222
    >>> type(x)
    <type 'long'>
    

    4、复数

    >>> x=1-2j
    >>> x.real
    1.0
    >>> x.imag
    -2.0 
    

    三、字符串类型

    1、基本使用

            1、用途:记录描述性质的状态,例如名字、性别、国籍等
            定义方式:在引号(' '," ",""" """,''' ''')内包含一串字符串 比如:s = 'hello' # s = str('hello')
            str功能可以把任意类型转换成str类型

    res = str([1,2,3])  # '[1,2,3]'
    print(type(res))  # <class 'str'>
    

    3、常用操作+内置的方法

    3.1 按索引取值

            按索引取值(正向取+反向取)只能取 不能改变原值

    s = 'hello word'
    print(s[0],type(s[0]))  # 'h'
    print(s[-1]) # 'd'
    # s[0] ='H'  # 不能修改
    
    # 非法操作
    # s[2222]
    # s[11] = 'A'
    

    3.2 切片

            切片(顾头不顾尾,步长) =>属于拷贝操作

    s = 'hello world'
    new_s = s[1:7]  # 从第1位切到第7位
    print(new_s)  # ello w
    print(s)  # hello world
    
    new_s = s[1:9:2]  # 1 3 5 7
    print(new_s)  # 'el o'
    
    new_s = s[:7:2]  # 0 2 4 6
    print(new_s)  # 'hlow'
    
    new_s = s[::2]  # 0 2 4 6 8
    print(new_s)  # 'hlowrd'
    
    new_s = s[::]  # 完整拷贝字符串,只留一个冒号就可以,new_s = s[:]
    print(new_s)  # 'hello world'
    

    3.3 长度len

    s = 'hello world'
    print(len(s))  # 11
    
    # res = print('123') # res = None 空 没有返回值
    # print(res)
    

    3.4 成员运算in和not in

    s = 'hello world'
    print('hel' in s)  # True
    print('sa' in s)  # False
    print('sa' not in s)  # True 语义明确 推荐使用
    print(not 'sa' in s)  # True
    

    3.5移除空白strip

    s = '           hello    '
    s.strip()
    print(s.strip())  # 'hello'
    print('           hello    '.strip())  # 'hello'
    print(s)  # '           hello    '  没有改变原字符串
    
    s = '  
        hello     	   '
    new_s = s.strip()
    print(new_s)  # 'hello'
    
    s = '           hello  world  '
    print(s)  # '           hello  world '
    print(s.strip())  # 'hello  world'
    
    # 去除左右两边的非空白字符
    print('*******++++------++  -**he ++ ll**o----   +++++****'.strip('=+- *'))
    msg='**/*=-**egon**-=()**'
    print(msg.strip('*/-=()'))  # 'he ++ ll**o'
    
    # 应用案例
    name = input('yor name:').strip()  # name = input('yor name:')
    pwd = input('yor name:').strip()  # pwd = input('yor name:')
    
    if name == 'sa' and pwd == '123':  # if name.strip() == 'sa' and pwd.strip() == '123':
        print('login successful')
    else:
        print('user or password error')
    

    3.6 切分split

            切分split:把字符串按照某个分割符切成一个列表
            默认分隔符是空格

    info='egon 18 male'
    res=info.split()
    print(res)  # ['egon', '18', 'male']
    

           指定分隔符

    userinfo = 'egon:123:18'
    res = userinfo.split(':')  # xplit(self sep maxsplit) 本身 分割符号 最大分割
    print(res, res[0])  # ['egon', '123', '18'] egon
    

           指定分隔次数(了解)

    info='egon:18:male'
    res=info.split(':',1)
    print(res)  # ['egon', '18:male']
    

    3.7 循环

    for i in 'hello':
        print(i)
    '''
    h
    e
    l
    l
    o
    '''
    

    4、拓展操作(了解掌握)

    4.1 strip,lstrip,rstrip

            strip,lstrip,rstrip 移除 左移除 右移除

    msg='***egon****'
    print(msg.strip('*'))  # egon
    print(msg.lstrip('*'))  # egon****
    print(msg.rstrip('*'))  # ***egon
    

    4.2 lower,upper(改变大小写)

    msg='AbbbCCCC'
    
    print(msg.lower())   # 全变小写
    print(msg.upper())   # 全变大写
    

    4.3 startswith,endswith(判断对应的值是否以这个开头/结尾)

    print("alex is sb".startswith("alex"))  # True
    print("alex is sb".endswith('sb'))  # True
    

    4.4 split,rsplit(将字符串切成列表 左切 右切)

    info="egon:18:male"  # 不设数量就是全切
    print(info.split(':',1))  # ["egon","18:male"]
    print(info.rsplit(':',1))  # ["egon:18","male"]
    

    4.5 join(把纯字符串列表拼接成字符串)

    l=['egon', '18', 'male']
    res=l
    res=''.join(l)
    print(res)  # egon18male
    res="-".join(l) # 按照某个分隔符号,把元素全为字符串的列表拼接成一个大字符串
    print(l)  # ['egon', '18', 'male']
    print(res)  # egon-18-male
    

    4.6 replace(修改内容)

    msg = "you can you up no can no bb"
    print(msg.replace("you", "YOU", ))  # YOU can YOU up no can no bb
    print(msg.replace("you", "YOU", 1))  # YOU can you up no can no bb
    print(msg)  # 原内容不会改变 you can you up no can no bb
    
    # 应用 将*和空格去掉
    msg = '******hello world******'
    res= msg.replace('*','').replace(' ','')
    print(res)  # helloworld
    res=msg.strip('*').replace(' ','')
    print(res)  # helloworld
    

    4.7 format的三种玩法

            1) %s的方式

    name = "sa"
    age = 18
    res1="my name is %s my age is %s" % (name,age)
    print(res1)  # my name is sa my age is 18
    

            2) format的方式

    name = 'sa'
    age = 18
    res1 = 'my name is {} my age is {}'.format(name, age)
    print(res1)  # my name is sa my age is 18
    res1 = '{0}{0}{0}{1}'.format(name, age)
    print(res1)  # sasasa18
    res1 = 'my name is {x} my age is {y}'.format(y=age, x=name)
    print(res1)  # my name is sa my age is 18
    
    res1 = 'my name is {x} my age is {y}'.format(y=18, x='sa')  # 不需要定义变量名 这种2.6后才有
    print(res1)  # my name is sa my age is 18
    

            3) f' ' (效果跟format一样 这是python3版本后才出现的)

    name = 'sa'
    age = 18
    res1 = f'my name is {name} my age is {age}'
    print(res1)  # my name is sa my age is 18
    

    4.9 f' ' 的补充(了解)'

            f搭配{}可以执行字符串中的代码

    res = f'{len("hello")}'  
    print(res)  # 5
    
    res = len('hello')
    print(res)  # 5
    
    f'{print("hello")}'  # hello
    

            f包含的字符串可以放到多行

    name = 'sa'
    age = 18
    
    res1 = f'my name is {name}' 
           f'my age is {age}'  # my name is sa my age is 18
    print(res1)  # my name is samy age is 18
    

           {}内不能有、以及# 详细了解https://zhuanlan.zhihu.com/p/110406030

    print(f'my name is {{egon}}')  # my name is {egon}
    print('胜率是 %s%%' % 70) # s后的第一个百分号是取消第二个百分号的定义 让他显示出了%
    # 胜率是 70%
    

    4.10 isdigit:判断字符串是否由纯数字组成

    print("adsf123".isdigit())  # False
    print("123".isdigit())  # True
    print("12.3".isdigit())  # False
    

           案例应用

    age = input('>>>: ') # age = "        18     "
    if age.isdigit():  # 先判断是否纯数字 再去判断年龄
        age=int(age)
        if age > 18:
            print('猜大了')
        elif age < 18:
            print('猜小了')
        else:
            print('猜对了')
    else:
        print('必须输入数字,小垃圾')
    

    4.11 find,rfind,index,rindex,count(找到返回起始索引)

           找到返回起始索引

    print(msg.find('e'))  # 2 返回要查找的字符串在大字符串中的起始索引
    print(msg.find('egon'))  # 6 e在列表第六位
    print(msg.index('e'))  # 1
    print(msg.index('egon'))  # 6
    

           找不到

    print(msg.find('xxx')) # 返回-1,代表找不到
    print(msg.index('xxx')) # 抛出异常
    
    msg='hello egon hahaha egon、 egon'
    print(msg.count('egon'))   # 3 单词的个数
    

    4.12 center,ljust,rjust,zfill

    print('egon'.center(30,'*'))  # *************egon*************
    print('egon'.ljust(30,'*'))  # egon**************************
    print('egon'.rjust(30,'*'))  # **************************egon
    print('egon'.zfill(10))  # 000000egon
    

    4.13 expandtabs

    msg='hello	world'
    print(msg.expandtabs(4)) # hello   world 设置制表符代表的空格数为2
    

    4.14 captalize,swapcase,title

    print("hello world Egon".capitalize())  # 将字符串的第一个字母变成大写,其他字母变小写
    print("Hello worLd EGon".swapcase())  # 对字符串的大小写字母进行转换。
    print("hello world egon".title())  # 所有单词的首个字母转化为大写,其余字母均为小写
    

    4.15 is系列

    print('abc'.islower())  # True 判断是否全是小写
    print('ABC'.isupper())  # True 判断是否全是大写
    print('Hello World'.istitle())  # True 判断每个字母开头是否大写
    print('123123aadsf'.isalnum())  # True 字符串由字母或数字组成结果为True
    print('ad'.isalpha())  # True 字符串由由字母组成结果为True
    print('     '.isspace())  # True 字符串由空格组成结果为True
    print('print'.isidentifier())  # True isidentifier() 方法用于判断字符串是否是有效的 Python 标识符,可用来判断变量名是否合法。
    print('age_of_egon'.isidentifier())  # True 
    print('1age_of_egon'.isidentifier())  # False
    

    4.16 识别

    num1=b'4' #bytes
    num2=u'4' #unicode,python3中无需加u就是unicode
    num3='四' #中文数字
    num4='Ⅳ' #罗马数字
    
    # isdigit只能识别:num1、num2
    print(num1.isdigit()) # True
    print(num2.isdigit()) # True
    print(num3.isdigit()) # False
    print(num4.isdigit()) # False
    
    # isnumberic可以识别:num2、num3、num4
    print(num2.isnumeric()) # True
    print(num3.isnumeric()) # True
    print(num4.isnumeric()) # True
    
    # isdecimal只能识别:num2
    print(num2.isdecimal()) # True
    print(num3.isdecimal()) # False
    print(num4.isdecimal()) # False
    
  • 相关阅读:
    Vue DatePicker和不可用
    API图片路径和超链接语义化转换
    jQuery常用插件大全
    前端面试必备技巧整理
    堆与堆排序/Heap&Heap sort
    第k大的数
    POJ 2083 Fractal 分形题目
    最大子数组问题/Maximum Subarray
    一个简单的随机数生成算法
    成绩排序
  • 原文地址:https://www.cnblogs.com/liuxinging/p/13281029.html
Copyright © 2011-2022 走看看