• python3 字符串format


    python 内置的format方法相当的强大,这里举一些比较有用的方法

    #!/usr/bin/env python
    #coding:utf-8
    #@Author:Andy
    
    
    # str.format()
    
    # {} 占位符
    
    print("I'm {}".format('andy'))
    # output I'm andy
    
    # {0} 数字形式
    print("He's {0} years old {1} years older than me.".format(25, 5))
    # output : He's 25 years old 5 years older than me.
    
    # 数字的顺序是可心修改变的,但这时后面参数也就跟着变
    print("He's {1} years old {0} years older than me.".format(5, 25))
    # output : He's 25 years old 5 years older than me.
    
    # 关键字
    print("His name is {name} and {age} years old ".format(name="andy", age=20))
    # output : His name is andy and 20 years old
    
    # 数字与关键字混合使用
    print("His name is {0} and {age} years old ".format('andy', age=20))
    #output : His name is andy and 20 years old
    
    # 这里的format表现与python 函数中的位置参数,关键字参数很相似
    
    # 格式控制,高级字符串控制
    
    #  包含的可靠参数有:[fill,align,sign,0,width,.precision,type]
    # fill 要填充的字符
    # align 对齐方式, < ^ > 分别表示左中右
    # sign 取值有1:+,所有数字签名都要加上符号;2:-,默认值,只在负数签名加符号;3:空格,在正数前面加上一个空格;
    # 用0填充数值前的空白
    # 宽度
    # precision 精度的位数
    # type 数据类型
    
    print("{:-^10}".format('*'))
    # output: ----*-----
    

    !r 就是  repr --->%r
    !s 就是 str  --->%s
    !a 就是 ascii ---%a

    这三个标志是使用后面的方法作用在前面的值上:

    看下面这个例子:

    s = "This is {0!a} {1!s} {2!r}".format('a','b','c')
    s
    Out[7]: "This is 'a' b 'c'"
    

     仔细看,a,b,c的表示方式并不相同.

    在3.1版本后:{0} {1} {2} 中的索引可以省略,直接写成:{}{}{}

    "{0}{1}{2}".format('a', 'b', 'c')
    Out[11]: 'abc'
    "{}{}{}".format('a','b','c')
    Out[12]: 'abc'
    
  • 相关阅读:
    Apache 阿帕奇 配置运行环境
    2019年6月多校联训b层——搜索算法 Problem A 宽搜 营救
    西安集训B Day1 test 问题 C: 小明的城堡
    西安集训B层Day1 test 问题 A: 旅行日记
    二分答案—洛谷P1182 数列分段`Section II`
    2019.5.25 Noip模拟测试2 T2题解
    2019.5.25 Noip模拟测试2 T1题解
    DP专题练习 toasting
    2019.5.1 DP专题训练 山峰数(hill)
    React 点击按钮显示div与隐藏div
  • 原文地址:https://www.cnblogs.com/Andy963/p/6977886.html
Copyright © 2020-2023  润新知