python的format怎么用-Python教程

资源魔 34 0

python的format怎样用?

python的format函数用法

它加强了字符串格局化的性能。根本语法是经过 {} 以及 : 来替代之前的 % 。format 函数能够承受没有限个参数,地位能够没有按程序。

**例一:**format 函数能够承受没有限个参数,地位能够没有按程序。

"{} {}".format("hello", "world")    # 没有设置指定地位,按默许程序
运转后果:'hello world'
 "{0} {1}".format("hello", "world")  # 设置指定地位
运转后果:'hello world'
"{1} {0} {1}".format("hello", "world")  # 设置指定地位
运转后果:'world hello world'

例二:也能够设置参数。

print("网站名:{name}, 地点 {url}".format(name="Python教程", url="www.py.cn"))
# 经过字典设置参数
site = {"name": "Python教程", "url": "www.py.cn"}
print("网站名:{name}, 地点 {url}".format(**site))
# 经过列表索引设置参数
my_list = ['Python教程', 'www.py.cn']
print("网站名:{0[0]}, 地点 {0[1]}".format(my_list))  # "0" 是必需的
运转后果:
网站名:Python教程, 地点 www.py.cn
网站名:Python教程, 地点 www.py.cn
网站名:Python教程, 地点 www.py.cn

例三:也能够向 str.format() 传入工具:

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)

‘{:b}’.format(11) 1011

‘{:d}’.format(11) 11

11的进制 ‘{:o}’.format(11) 13

‘{:x}’.format(11) b

‘{:#x}’.format(11) 0xb

‘{:#X}’.format(11) 0XB

^, <, > 辨别是居中、左对齐、右对齐,前面带宽度, : 号前面带填充的字符,只能是一个字符,没有指定章默许是用空格填充。

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

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

例五:

给你一个字典:

t={‘year’:’2013’,’month’:’9’,’day’:’30’,’hour’:’16’,’minute’:’45’,’second’:’2’}

请按这样的格局输入:2013-09-30 16:45:02

def data_to_str(d):
    '''
    :param d: 日期字典
    :return: str 格局化后的日期
    '''
    s1='{} {:>02} {:>02}'.format(t['year'],t['month'],t['day'])
    s2='{} {:>02} {:>02}'.format(t['hour'],t['minute'],t['second'])
    print(s1,s2)
    print('-'.join(s1.split()),end=' ')
    print(':'.join(s2.split()))
    return 0
t={'year':'2013','month':'9','day':'30','hour':'16','minute':'45','second':'2'}
print(data_to_str(t))

运转后果:

2013 09 30 16 45 02
2013-09-30 16:45:02

相干保举:《Python教程》

以上就是python的format怎样用的具体内容,更多请存眷资源魔其它相干文章!

标签: Python python教程 python编程 python使用问题

抱歉,评论功能暂时关闭!