zoukankan      html  css  js  c++  java
  • Python 数据类型

    一、python的字符串format

    字符串是Python程序重要的数据类型,到目前为止,我们输出的字符串的内容都是固定的,但有时候通过字符串输出的内容不是固定的,这个时候需要使用format来处理字符串,输出不固定的内容。
    字符串format由两个部分组成,字符串模板和模板数据内容组成,通过大括号{},就可以把模板数据内容嵌到字符串模板对应的位置。

    # 字符串模板
    template = 'Hello {}'
    # 模板数据内容
    world = 'World'
    result = template.format(world)
    print(result) # ==> Hello World
    

    如果模板中{}比较多,则容易错乱,那么在format的时候也可以指定模板数据内容的顺序。

    # 指定顺序
    template = 'Hello {0}, Hello {1}, Hello {2}, Hello {3}.'
    result = template.format('World', 'China', 'Beijing', 'imooc')
    print(result) # ==> Hello World, Hello China, Hello Beijing, Hello imooc.
    # 调整顺序
    template = 'Hello {3}, Hello {2}, Hello {1}, Hello {0}.'
    result = template.format('World', 'China', 'Beijing', 'imooc')
    print(result) # ==> Hello imooc, Hello Beijing, Hello China, Hello World.
    

    除了使用顺序,还可以指定对应的名字,使得在format过程更加清晰。

    # 指定{}的名字w,c,b,i
    template = 'Hello {w}, Hello {c}, Hello {b}, Hello {i}.'
    world = 'World'
    china = 'China'
    beijing = 'Beijing'
    imooc = 'imooc'
    # 指定名字对应的模板数据内容
    result = template.format(w = world, c = china, b = beijing, i = imooc)
    print(result) # ==> Hello World, Hello China, Hello Beijing, Hello imooc.
    

      

    二、Python的字符串切片

    字符串由一个个字符组成,每一个字符都有一个唯一的位置。比如字符串'ABC',第一个字符是A,第二个字符是B,第三个字符是C
    因此我们可以使用位置的方式取出字符串中特定位置的字符,按照位置取字符串的方式使用中括号[]访问,这个时候可以把字符串看作是一个列表(一种新的数据类型,在后面会继续学习),不过需要注意的是,在程序的世界中,计数是从0开始的,使用0来表示第一个。

    s = 'ABC'
    a = s[0] # 第一个
    b = s[1] # 第二个
    c = s[2] # 第三个
    print(a) # ==> A
    print(b) # ==> B
    print(c) # ==> C
    

      

    有时候,我们会想获取字符串的一部分(子串),这个时候我们采取切片的方式获取,切片需要在中括号[]中填入两个数字,中间用冒号分开,表示子串的开始位置和结束位置,并且这是半闭半开区间,不包括最后的位置。

    ab = s[0:2] # 取字符串s中的第一个字符到第三个字符,不包括第三个字符
    print(ab) # ==> AB
    

    我们定义一个更长的字符串,了解切片更多的细节。

    s = 'ABCDEFGHIJK'
    abcd = s[0:4] # 取字符串s中的第一个字符到第五个字符,不包括第五个字符
    print(abcd) # ==> ABCD
    cdef = s[2:6] # 取字符串s中的第三个字符到第七个字符,不包括第七个字符
    print(cdef) # ==> CDEF
    

    原文:https://www.imooc.com/code/21959

  • 相关阅读:
    Vue 2.x windows环境下安装
    VSCODE官网下载缓慢或下载失败 解决办法
    angular cli 降级
    Win10 VS2019 设置 以管理员身份运行
    XSHELL 连接 阿里云ECS实例
    Chrome浏览器跨域设置
    DBeaver 执行 mysql 多条语句报错
    DBeaver 连接MySql 8.0 报错 Public Key Retrieval is not allowed
    DBeaver 连接MySql 8.0报错 Unable to load authentication plugin 'caching_sha2_password'
    Linux系统分区
  • 原文地址:https://www.cnblogs.com/sucretan2010/p/14779234.html
Copyright © 2011-2022 走看看