zoukankan      html  css  js  c++  java
  • python中使用%与.format格式化文本

    初学python,看来零零碎碎的格式化文本的方法,总结一下python中格式化文本的方法。使用不当的地欢迎指出谢谢。

    1、首先看使用%格式化文本

    常见的占位符:

    常见的占位符有:
    %d    整数
    %f    浮点数
    %s    字符串
    %x    十六进制整数

    使用方法:

    >>> 'Hello, %s' % 'world'
    'Hello, world'
    >>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
    'Hi, Michael, you have $1000000.'

    使用的时候不知道写什么的地方直接使用 %s 进行代替,语句的末尾加上 %() 括号里面直接填写内容即可(字符串加上引号,中间用“,”分割),如果只有一个%?,括号可以省略。

    高级一点的用法:

    格式化整数指定是否补零:

    首先看代码:

    >>> '%d-%d' % (3, 23)
    '3-23'
    >>> '%2d-%2d' % (3, 23)
    ' 3-23'
    >>> '%3d-%3d' % (3, 23)
    '  3- 23'
    >>> '%4d-%4d' % (3, 23)
    '   3-  23'
    >>> '%01d-%01d' % (3, 23)
    '3-23'
    >>> '%02d-%02d' % (3, 23)
    '03-23'
    >>> '%03d-%03d' % (3, 23)
    '003-023'
    >>> '%04d-%04d' % (3, 23)
    '0003-0023'
    >>> 

    可以看得出来,d前面的数字用来指定占位符,表示被格式化的数值占用的位置数量(字节还是什么不知道这样的表述是否正确),指定之后比如%3d,代表这个整数要占用3个位置,前面如果有0代表占用的地方使用0补齐,没有就使用空格补齐。指定的空间位置小于实际的数字大小,以实际占用的位置大小为准。

    指定小数的位数:

    >>> '%.f' % 3.1415926
    '3'
    >>> '%.1f' % 3.1415926
    '3.1'
    >>> '%.2f' % 3.1415926
    '3.14'
    >>> '%.3f' % 3.1415926
    '3.142'
    >>>

    可以看出.后面的数字用来表示保留的小数点的位数,".1"代表保留小数点后面一位小数。

    如果不确定应该用什么,%s永远起作用,它会把任何数据类型转换为字符串:

    >>> 'Age: %s. Gender: %s' % (25, True)
    'Age: 25. Gender: True'

    有些时候,字符串里面的%是一个普通字符怎么办?这个时候就需要转义,用%%来表示一个%

    >>> 'growth rate: %d %%' % 7
    'growth rate: 7 %'

    尝试使用其他方法对%进行转义,但是好像没有用,有什么其他方法欢迎评论。

    2、使用format 方法进行格式化

    代码演示:

    age = 25
    name = 'Swaroop' print('{0} is {1} years old'.format(name, age)) print('Why is {0} playing with that python?'.format(name))

    位置使用{1}按照使用的顺序写好,后面格式使用 .format()  写好对应的参数即可。

    输出结果:

    Swaroop is 25 years old
    Why is Swaroop playing with that python?

    其实也可以使用第一种方法实现:

    age = 25
    name = 'Swaroop'
    print('%s is %s years old'%(name, age))
    print('Why is %s playing with that python?'%(name))

    输出

    Swaroop is 25 years old
    Why is Swaroop playing with that python?

    实现的结果都是一样的。

     具体两者的区别参看 http://python.jobbole.com/87065/

  • 相关阅读:
    86. Partition List
    328. Odd Even Linked List
    19. Remove Nth Node From End of List(移除倒数第N的结点, 快慢指针)
    24. Swap Nodes in Pairs
    2. Add Two Numbers(2个链表相加)
    92. Reverse Linked List II(链表部分反转)
    109. Convert Sorted List to Binary Search Tree
    138. Copy List with Random Pointer
    为Unity的新版ugui的Prefab生成预览图
    ArcEngine生成矩形缓冲区
  • 原文地址:https://www.cnblogs.com/engeng/p/6605936.html
Copyright © 2011-2022 走看看