Python format 格式化函数

Python 字符串 Python 字符串


Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {}: 来代替以前的 %

format 函数可以接受不限个参数,位置可以不按顺序。

实例

>>> {} {} . format ( hello , world ) # 不设置指定位置,按默认顺序 hello world >>> {0} {1} . format ( hello , world ) # 设置指定位置 hello world >>> {1} {0} {1} . format ( hello , world ) # 设置指定位置 world hello world

也可以设置参数:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- print ( 网站名:{name}, 地址 {url} . format ( name = 菜鸟教程 , url = www.runoob.com ) ) # 通过字典设置参数 site = { name : 菜鸟教程 , url : www.runoob.com } print ( 网站名:{name}, 地址 {url} . format ( ** site ) ) # 通过列表索引设置参数 my_list = [ 菜鸟教程 , www.runoob.com ] print ( 网站名:{0[0]}, 地址 {0[1]} . format ( my_list ) ) # “0” 是必须的

输出结果为:

网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com

也可以向 str.format() 传入对象:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- class AssignValue ( object ) : def __init__ ( self , value ) : self . value = value my_value = AssignValue ( 6 ) print ( value 为: {0.value} . format ( my_value ) ) # “0” 是可选的

输出结果为:

value 为: 6

数字格式化

下表展示了 str.format() 格式化数字的多种方法:

>>> print("{:.2f}".format(3.1415926));
3.14
数字格式输出 描述
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:+.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)
5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法
13 {:10d}         13 右对齐 (默认, 宽度为10)
13 {:<10d} 13 左对齐 (宽度为10)
13 {:^10d}     13 中间对齐 (宽度为10)
11
'{:b}'.format(11)
'{:d}'.format(11)
'{:o}'.format(11)
'{:x}'.format(11)
'{:#x}'.format(11)
'{:#X}'.format(11)
1011
11
13
b
0xb
0XB
进制

^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

+ 表示在正数前显示 +,负数前显示 -  (空格)表示在正数前加空格

b、d、o、x 分别是二进制、十进制、八进制、十六进制。

此外我们可以使用大括号 {} 来转义大括号,如下实例:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- print ( {} 对应的位置是 {{0}} . format ( runoob ) )

输出结果为:

runoob 对应的位置是 {0}

Python 字符串 Python 字符串

        </div>

    </div>

    <div class="previous-next-links">
        <div class="previous-design-link"><a href="http://www.runoob.com/python/python-numbers.html"><i class="fa fa-arrow-left" aria-hidden="true" style="font-size:16px;"></i></a> <a title="Python Number(数字)" href="http://www.runoob.com/python/python-numbers.html" rel="prev">Python Number(数字)</a> </div>
        <div class="next-design-link"><a title="Python 列表(List)" href="http://www.runoob.com/python/python-lists.html" rel="next">Python 列表(List)</a> <a href="http://www.runoob.com/python/python-lists.html"><i class="fa fa-arrow-right" aria-hidden="true" style="font-size:16px;"></i></a></div>
    </div>
    <!-- 笔记列表 -->
    <style>

.wrapper {
/text-transform: uppercase; /
background: #ececec;
color: #555;
cursor: help;
font-family: “Gill Sans”, Impact, sans-serif;
font-size: 20px;
position: relative;
text-align: center;
width: 200px;
-webkit-transform: translateZ(0); /* webkit flicker fix */
-webkit-font-smoothing: antialiased; /* webkit text rendering fix */
}

.wrapper .tooltip {
white-space: nowrap;
font-size: 14px;
text-align: left;
background: #96b97d;
bottom: 100%;
color: #fff;
display: block;
left: -25px;
margin-bottom: 15px;
opacity: 0;
padding: 14px;
pointer-events: none;
position: absolute;

-webkit-transform: translateY(10px);
-moz-transform: translateY(10px);
-ms-transform: translateY(10px);
-o-transform: translateY(10px);
transform: translateY(10px);
-webkit-transition: all .25s ease-out;
-moz-transition: all .25s ease-out;
-ms-transition: all .25s ease-out;
-o-transition: all .25s ease-out;
transition: all .25s ease-out;
-webkit-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
-moz-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
-ms-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
-o-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
}
.tooltip a {
color:#fff;
}
/* This bridges the gap so you can mouse into the tooltip without it disappearing */
.wrapper .tooltip:before {
bottom: -20px;
content: ” “;
display: block;
height: 20px;
left: 0;
position: absolute;
width: 100%;
}

/* CSS Triangles - see Trevor’s post */
.wrapper .tooltip:after {
border-left: solid transparent 10px;
border-right: solid transparent 10px;
border-top: solid #96b97d 10px;
bottom: -10px;
content: ” “;
height: 0;
left: 20%;
margin-left: -13px;
position: absolute;
width: 0;
}
.wrapper .tooltip1 {
margin-left: 50px;
padding-top: 0px;
}
.wrapper:hover .tooltip {
opacity: 1;
pointer-events: auto;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px);
}

/* IE can just show/hide with no transition */
.lte8 .wrapper .tooltip {
display: none;
}

.lte8 .wrapper:hover .tooltip {
display: block;
}

1 篇笔记

  1. #1

       like

      127***9424@qq.com

    % 操作符,格式如下:

    %[(name)][flags][width].[precision]typecode
    • (name) 为命名
    • flags 可以有 +,-,’ ‘或 0。+ 表示右对齐。- 表示左对齐。’ ’ 为一个空格,表示在正数的左侧填充一个空格,从而与负数对齐。0 表示使用 0 填充。
    • width 表示显示宽度
    • precision 表示小数点后精度

    以下是类型码:

    %s    字符串 (采用str()的显示)
    %r    字符串 (采用repr()的显示)
    %c    单个字符
    %b    二进制整数
    %d    十进制整数
    %i    十进制整数
    %o    八进制整数
    %x    十六进制整数
    %e    指数 (基底写为e)
    %E    指数 (基底写为E)
    %f    浮点数
    %F    浮点数,与上相同%g    指数(e)或浮点数 (根据显示长度)
    %G    指数(E)或浮点数 (根据显示长度)
    %%    字符"%"

    举例

    >>> print("%6.3f" % 2.3)
     2.300
    • 第一个 % 后面的内容为显示的格式说明,6 为显示宽度,3 为小数点位数,f 为浮点数类型
    • 第二个 % 后面为显示的内容来源,输出结果右对齐,2.300 长度为 5,故前面有一空格
    >>> print("%+10x" % 10)
        +a

    x 为表示 16 进制,显示宽度为 10,前面有 8 个空格。

    >>>print("%-5x" % -10)
    -a  

    %-5x 负号为左对齐,显示宽度为 5,故 -a 后面有 3 个空格

    >>>pi=3.1415
    >>>print ("pi的值是%s"%pi)
    pi的值是3.1415
    
    >>>print ("pi的值是%.8f"%pi)
    pi的值是3.14150000

    上面的 width, precision 为两个整数。我们可以利用 *,来动态代入这两个量。比如:

    >>> print("%10.*f" % (4, 1.2))
      1.2000

    以下是补充

    简单的说,这是一种将其他变量置入字符串特定位置以生成新字符串的操作,比如说:

    >>> n = "Runoob"
    >>> "My name is %s" % n
    'My name is Runoob'

    这段代码首先定义了一个名为 n 的变量,内容为 Runoob。然后下方的字符串中有一个 %s,他的含义是“这里将被替换成一个新的字符串”,用作替换的内容放在字符串后面的%后面,就是那个 n。所以最终这个字符串会变成 My name is Runoob。

    like

       like

      127***9424@qq.com

    1个月前 (08-02)

点我分享笔记

笔记需要是本篇文章的内容扩展!


<form id="commentform" style="display:none;" action="/wp-content/themes/runoob/option/addnote.php" method="post"><div id="comment-status"></div>
    <div class="comt">
        <div class="comt-title">
            <i class="fa fa-user-circle" aria-hidden="true" style="font-size:36px;"></i>                <p><a id="cancel-comment-reply-link" href="javascript:;">取消</a></p>
        </div>
        <div class="comt-box">
        <div class="simditor">


写笔记…



选择程序语言 BashC++C#CSSErlangLessSassDiffCoffeeScriptHTML,XMLJSONJavaJavaScriptMarkdownObjective CPHPPerlPythonRubySQL

            <div class="comt-ctrl">
                <div class="comt-tips"><input name="comment_post_ID" id="comment_post_ID" type="hidden" value="18630">