• python入门008


    一、for循环

    作用:for循环是因为在循环取值(即遍历值)时for循环比while循环的使用更为简洁

    1.for循环语法:

    for 变量名 in 可迭代对象: # 此时只需知道可迭代对象可以是字符串列表字典,我们之后会专门讲解可迭代对象
        代码一
        代码二
        ...
    #例1
    for item in ['a','b','c']:
        print(item)
    # 运行结果
    a
    b
    c
    
    # 参照例1来介绍for循环的运行步骤
    # 步骤1:从列表['a','b','c']中读出第一个值赋值给item(item=‘a’),然后执行循环体代码
    # 步骤2:从列表['a','b','c']中读出第二个值赋值给item(item=‘b’),然后执行循环体代码
    # 步骤3: 重复以上过程直到列表中的值读尽
    

    2.应用案例:

    案例一:打印数字0-9

    for i in range(1,10):#顾头不顾尾1 2 3 4 5 6 7 8 9
        print(i)
    

    案例二:遍历字典

    for i in ['egon',18,'male','sleep','play']:
        print(i)
    

    案例三:for循环嵌套

    for i in range(5):
        if i == 3:continue
        print('外层循环-------',i)
        for x in range(5):
            print('内层循环----',x)
    

    注意:break 与 continue也可以用于for循环,使用语法同while循环

    二、数字类型int与float

    1.定义:

    整型int的定义
    age=10  # 本质age = int(10)
    浮点型float的定义
    salary=3000.3  # 本质salary=float(3000.3)
    # 注意:名字+括号的意思就是调用某个功能,比如
    # print(...)调用打印功能
    # int(...)调用创建整型数据的功能
    # float(...)调用创建浮点型数据的功能
    

    2.类型转换:

    int可以将由纯整数构成的字符串直接转换成整型,若包含其他任意非整数符号,则会报错
    比如

    msg='666'
    print(type(msg))
    msg1=int(msg)
    print(type(msg1))
    

    输出结果:

    <class 'str'>
    <class 'int'>
    
    

    3.使用:

    数字类型主要就是用来做数学运算与比较运算,因此数字类型除了与运算符结合使用之外,并无需要掌握的内置方法

    三、字符串

    1.定义:在单引号双引号三引号内包含一串字符,列如

    name1 = 'jason'  # 本质:name = str('任意形式内容')
    name2 = "lili"  # 本质:name = str("任意形式内容")
    name3 = """ricky"""  # 本质:name = str("""任意形式内容""")
    

    2.类型转换:str()可以将任意数据类型转换成字符串类型,列如

    msg=['egon',18,'male','sleep','play']
    print(type(msg))
    msg1=str(msg)
    print(type(msg1))
    输出结果:
    <class 'list'>
    <class 'str'>
    

    3.使用:

    3.1 优先掌握的操作

    >>> str1 = 'hello python!'
    
    
    # 1.按索引取值(正向取,反向取):
    # 1.1 正向取(从左往右)
    >>> str1[6]
    p
    # 1.2 反向取(负号表示从右往左)
    >>> str1[-4]
    h
    # 1.3 对于str来说,只能按照索引取值,不能改
    >>> str1[0]='H' # 报错TypeError
    
    
    # 2.切片(顾头不顾尾,步长)
    # 2.1 顾头不顾尾:取出索引为0到8的所有字符
    >>> str1[0:9]  
    hello pyt
    # 2.2 步长:0:9:2,第三个参数2代表步长,会从0开始,每次累加一个2即可,所以会取出索引0、2、4、6、8的字符
    >>> str1[0:9:2]  
    hlopt 
    # 2.3 反向切片
    >>> str1[::-1]  # -1表示从右往左依次取值
    !nohtyp olleh
    
    # 3.长度len
    # 3.1 获取字符串的长度,即字符的个数,但凡存在于引号内的都算作字符)
    >>> len(str1) # 空格也算字符
    13
    
    # 4.成员运算 in 和 not in    
    # 4.1 int:判断hello 是否在 str1里面
    >>> 'hello' in str1  
    True
    # 4.2 not in:判断tony 是否不在 str1里面
    >>> 'tony' not in str1 
    True
    
    # 5.strip移除字符串首尾指定的字符(默认移除空格)
    # 5.1 括号内不指定字符,默认移除首尾空白字符(空格、
    、	)
    >>> str1 = '  life is short!  '
    >>> str1.strip()  
    life is short!
    
    # 5.2 括号内指定字符,移除首尾指定的字符
    >>> str2 = '**tony**'  
    >>> str2.strip('*')  
    tony
    
    # 6.切分split
    # 6.1 括号内不指定字符,默认以空格作为切分符号
    >>> str3='hello world'
    >>> str3.split()
    ['hello', 'world']
    # 6.2 括号内指定分隔字符,则按照括号内指定的字符切割字符串
    >>> str4 = '127.0.0.1'
    >>> str4.split('.')  
    ['127', '0', '0', '1']  # 注意:split切割得到的结果是列表数据类型
    
    
    # 7.循环
    >>> str5 = '今天你好吗?'
    >>> for line in str5:  # 依次取出字符串中每一个字符
    ...     print(line)
    ...
    今
    天
    你
    好
    吗
    ?
    

    3.2需要掌握的操作

    1.strip, lstrip, rstrip

    >>> str1 = '**tony***'
    
    >>> str1.strip('*')  # 移除左右两边的指定字符
    'tony'
    >>> str1.lstrip('*')  # 只移除左边的指定字符
    tony***
    >>> str1.rstrip('*')  # 只移除右边的指定字符
    **tony
    

    2.lower(),upper()

    >>> str2 = 'My nAme is tonY!'
    
    >>> str2.lower()  # 将英文字符串全部变小写
    my name is tony!
    >>> str2.upper()  # 将英文字符串全部变大写
    MY NAME IS TONY!
    

    3.startswith,endswith

    >>> str3 = 'tony jam'
    
    # startswith()判断字符串是否以括号内指定的字符开头,结果为布尔值True或False
    >>> str3.startswith('t') 
    True
    >>> str3.startswith('j')
    False
    # endswith()判断字符串是否以括号内指定的字符结尾,结果为布尔值True或False
    >>> str3.endswith('jam')
    True
    >>> str3.endswith('tony')  
    

    4.格式化输出之format

    之前我们使用%s来做字符串的格式化输出操作,在传值时,必须严格按照位置与%s一一对应,而字符串的内置方法format则提供了一种不依赖位置的传值方式

    案例

    # format括号内在传参数时完全可以打乱顺序,但仍然能指名道姓地为指定的参数传值,name=‘tony’就是传给{name}
    >>> str4 = 'my name is {name}, my age is {age}!'.format(age=18,name='tony')
    >>> str4  
    'my name is tony, my age is 18!'
    
    >>> str4 = 'my name is {name}{name}{name}, my age is {name}!'.format(name='tony', age=18)
    >>> str4  
    'my name is tonytonytony, my age is tony!'
    

    5.split,rsplit

    # split会按照从左到右的顺序对字符串进行切分,可以指定切割次数
    >>> str5='C:/a/b/c/d.txt'
    >>> str5.split('/',1)
    ['C:', 'a/b/c/d.txt']  
    
    # rsplit刚好与split相反,从右往左切割,可以指定切割次数
    >>> str5='a|b|c'
    >>> str5.rsplit('|',1)
    ['a|b', 'c']
    

    6.join

    # 从可迭代对象中取出多个字符串,然后按照指定的分隔符进行拼接,拼接的结果为字符串
    >>> '%'.join('hello') # 从字符串'hello'中取出多个字符串,然后按照%作为分隔符号进行拼接
    'h%e%l%l%o'
    >>> '|'.join(['tony','18','read'])  # 从列表中取出多个字符串,然后按照*作为分隔符号进行拼接
    'tony|18|read'
    

    7.replace

    # 用新的字符替换字符串中旧的字符
    >>> str7 = 'my name is tony, my age is 18!'  # 将tony的年龄由18岁改成73岁
    >>> str7 = str7.replace('18', '73')  # 语法:replace('旧内容', '新内容')
    >>> str7
    my name is tony, my age is 73!
    
    # 可以指定修改的个数
    >>> str7 = 'my name is tony, my age is 18!'
    >>> str7 = str7.replace('my', 'MY',1) # 只把一个my改为MY
    >>> str7
    'MY name is tony, my age is 18!'
    

    8.isdigit

    # 判断字符串是否是纯数字组成,返回结果为True或False
    >>> str8 = '5201314'
    >>> str8.isdigit()
    True
    
    >>> str8 = '123g123'
    >>> str8.isdigit()
    False
    

    ok啦,今天学的够多得了/捂脸

  • 相关阅读:
    mysql应用技巧
    Python httplib学习
    桌标相关知识
    行业百科知识--Github
    Ghost win7 系统安装(虚拟机)
    记一次pycharm和vscode因网络问题插件下载失败的问题
    Pydiction补全插件
    MS17-010远程溢出漏洞(CVE-2017-0143)
    shell快速入门
    Yarn架构
  • 原文地址:https://www.cnblogs.com/linqiaobao/p/12457350.html
Copyright © 2020-2023  润新知