zoukankan      html  css  js  c++  java
  • Day1 字符串格式化

    1.占位符方式:
    占位符:
      %d   整数   %012d   数字位数至少长度为12位,不足的前面加0填充。
                    >>> 'Hello,%s,%012d' % ('a',1234567890123456)
                    'Hello,a,1234567890123456'
                    >>> 'Hello,%s,%012d' % ('a',123)
                    'Hello,a,000000000123'

      %f   浮点数   %.4f   小数点后保留2位,超出两位的四舍五入,不足两位的用0占位。
                    >>> 'Hello,%s,%.4f' % ('a',123.1234567)
                    'Hello,a,123.1235'
                    >>> 'Hello,%s,%.4f' % ('a',123.1)
                    'Hello,a,123.1000'

      %s   字符串       可以把任何类型转换为字符串,不确定用什么的时候%s永远好用。
                    在字符串中,需要输出%符号时, 用%转义, 通过%%来表示%符号。

      %x   十六进制数

    有几个占位符,后面就跟几个变量或值,顺序一一对应, 如:

        >>> 'Hello,%s' %'world'
        'Hello,world'
        >>> 'Hello,%s,%s' % ('world','worl2')
        'Hello,world,worl2'
        >>> 'Hello,%s,%s,%d' % ('world','worl2',120)
        'Hello,world,worl2,120'
        >>> 'Hello,%s,%s,%d,%f' % ('world','worl2',120,3.14)
        'Hello,world,worl2,120,3.140000'

    2.format()函数方式
    format()函数
      使用传入函数的参数,依次替换字符串内的顺序占位符, 略麻烦。

        >>> 'Hello,{0},{1},{2},hahahaha,{3},{4:05d},{5:.4f},end'.format('a',666,'aaa%%',22,33,1.23456)
        'Hello,a,666,aaa%%,hahahaha,22,00033,1.2346,end'

    个个原创文章

    欢迎讨论
    https://www.cnblogs.com/konggg/
    欢迎转载收藏,转载请注明来源,谢谢支持!
  • 相关阅读:
    noip宝藏
    [HNOI2008]玩具装箱TOY
    hdu 4372 Count the Buildings 轮换斯特林数
    bzoj 3000 Big Number 估算n!在k进制下的位数 斯特林公式
    自然数幂求和方法1:扰动法(求两次)
    斯特林数 学习笔记
    hdu 3625 Examining the Rooms 轮换斯特林数
    cf 472G Design Tutorial: Increase the Constraints 分块+压位/FFT
    chef and churu 分块 好题
    分块 学习笔记
  • 原文地址:https://www.cnblogs.com/konggg/p/8945745.html
Copyright © 2011-2022 走看看