Python 格式化输出 f/F,format,%的用法

python格式化输出 f/F,format,%的用法

集合的元素只支持数字、字符串和元组,这些都是Python不可变数据类型,而字典的key必须为不可变数据类型,如字符串、数字或元组;value可以是任意的数据类型。集合是一个无序的不重复元素序列,可以使用大括号“{ }”或者set()函数创建集合,但是创建一个空集合必须使用set()函数,不能使用大括号“{ }”,因为大括号“{ }”用来创建一个空字典。
《精通Python自动化编程》

# 变量
name = 'Li'
message = f"name:{name}"
print(message)

# 列表
list1 = ['Li', 8, [98, 99]]
result = f"姓名:{list1[0]},年龄:{list1[1]},语文成绩:{list1[2][0]},英语成绩:{list1[2][-1]}"
print(result)

# 字典
dict1 = {'age': 8, 'name': 'Li'}
result1 = f"姓名:{dict1['name']},年龄:{dict1['age']}"
print(result1)

# 元组
tuple1 = (99, "英语成绩", "Li")
result2 = f"{tuple1[2]}{tuple1[1]}:{tuple1[0]}"
print(result2)

# 日期
import datetime

today = datetime.datetime.now()
print(today)
result3 = f"今天是:{today:%Y-%m-%d} {today:%H:%M:%S}"
print(result3)

# python中格式化输出 %.4f 输出小数,即保留小数点后4位数字
# 浮点数
a = 10
b = 3
result4 = f"a/b的浮点值为:{float('%.4f' % (a / b))}"
print(result4)

https://www.jianshu.com/p/1aa33beedbcd
https://blog.csdn.net/qq_22613769/article/details/107953257

常用格式化符种类及描述:
| 符号 | 描述 |
|:-------------😐:-------------😐
| %c | 格式化字符(输出数值对应的ASCII码) |
| %s |格式化字符串 |
| %d | 格式化整数 |
| %x | 格式化十六进制数(小写) |
| %X | 格式化十六进制数(大写) |
| %o | 格式化八进制数 |
| %f | 格式化浮点数字,可以指定小数点精度 |
| %%|输出%号|

格式化构成字符串:

>>> tmp = '%c'%100    #'%c'%100, 将100转化为对应的ASCII码字符'd'
>>> print (tmp)
d
>>>
格式化字符串 :
>>> print ('HelloWorld')
HelloWorld
>>> phoneTypes = 'Xiaomi, Iphone, Oppo'
>>> print ('%s' % phoneTypes)
Xiaomi, Iphone, Oppo
>>> 
格式化输出整数:
>>> x = 10
>>> print ('%d' % x)                       #10进制
10
>>> print ('0x%x' % x)                     #16进制(小写)
0xa
>>> print ('0x%x' % (id(10)))              #对象的地址使用16进制表示
0x5094a580
>>> print ('0x%X' % x)                     #16进制(大写)
0xA
>>> print ('%o' % x)                       #8进制
12
百分比输出:
>>> print ('%d%' % 10)                            #直接使用%报错
Traceback (most recent call last):
  File "<pyshell#58>", line 1, in <module>
    print ('%d%' % 10)
ValueError: incomplete format
>>> 
>>> print ('%d%%' % 10)                           #使用%%可以正常输出
10%
格式化输出浮点数:
>>> pi = 3.1415926
>>> print ('%d' % pi)      #使用%d只能显示整数
3
>>> print ('%f' % pi)      #使用浮点显示
3.141593                   #小数点之后只显示6位
>>> print ('%1.7f' % pi)   #指定小数点显示7位
3.1415926
>>> print ('%1.8f' % pi)   #指定小数点显示8位,后面默认补0
3.14159260
print函数中的格式化输出的过程:
>>> x = 10
>>> y = 20
>>> z = 30
>>> print ('%d' % x)                          #%d是占位符,
10
>>> print ('x=%d, y=%d, z=%d' % (x, y, z))    #占位符的个数要和要显示对象数量一致,否则会报错
x=10, y=20, z=30
>>> print ('x=%d, y=%d, z=%d' % (x, y))       #占位符与显示对象不一致
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
print 制定占位符宽度:
>>> print ('x=%d y=%d z=%d' % (x, y, z))
x=10 y=20 z=30     #想要一种效果,x,y,z分割一定距离,例如:x=10      y=20      z=30
#制定占位符的宽度:
>>> print ('x=%5d y=%5d z=%5d' % (x, y, z))
x=   10 y=   20 z=   30
%nd的作用,请看下面输出:


>>> x = 1
>>> print ('x=%1d' % x)
x=1
>>> print ('x=%2d' % x)     #%2d,制定占位符宽度为2,右对齐
x= 1                        #=后面空一格
>>> print ('x=%3d' % x)
x=  1                       #=后面空两格
>>> x, y, z = 10, 20, 30
>>> print ('x=%5d y=%5d z=%5d' % (x, y, z))
x=   10 y=   20 z=   30      #我们想要:x=10      y=20      z=30这个效果
>>>
>>> print ('x=%-5d y=%-5d z=%-5d' % (x, y, z))  #输出左对齐:'-'
x=10    y=20    z=30

fprmat用法

相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’
https://www.cnblogs.com/fat39/p/7159881.html#tag1
https://blog.csdn.net/qq_22613769/article/details/107953257


1.位置匹配
(1)不带编号,即“{}”
(2)带数字编号,可调换顺序,即“{1}”、“{2}”
(3)带关键字,即“{a}”、“{tom}”

>>> print('{} {}'.format('hello','world'))                # 不带字段
hello world
>>> print('{0} {1}'.format('hello','world'))              # 带数字编号
hello world
>>> print('{0} {1} {0}'.format('hello','world'))          # 打乱顺序
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world'))  # 带关键字
world hello world

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')      # 3.1+版本支持
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')          # 可打乱顺序,注意前面有*号
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')       # 可重复
'abracadabra'

通过位置匹配

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)        #注意前面**号
'Coordinates: 37.24N, -115.81W'
>>>'Coordinates: {0[latitude]}, {0[longitude]}'.format(coord)     #结果同上,原理同下
'Coordinates: 37.24N, -115.81W'


>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'
>>> a = {'a': 'test_a', 'b': 'test_b'}
>>> 'X: {0[a]};  Y: {0[b]}'.format(a)
'X: test_a;  Y: test_b'

通过下标或key匹配参数


2.格式转换
‘b’ - 二进制。将数字以2为基数进行输出。
‘c’ - 字符。在打印之前将整数转换成对应的Unicode字符串。
‘d’ - 十进制整数。将数字以10为基数进行输出。
‘o’ - 八进制。将数字以8为基数进行输出。
‘x’ - 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母。
‘e’ - 幂符号。用科学计数法打印数字。用’e’表示幂。
‘g’ - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印。
‘n’ - 数字。当值为整数时和’d’相同,值为浮点数时和’g’相同。不同的是它会根据区域设置插入数字分隔符。
‘%’ - 百分数。将数值乘以100然后以fixed-point(‘f’)格式打印,值后面会有一个百分号。

>>> print('{0:b}'.format(3))
11
>>> print('{:c}'.format(20))

>>> print('{:d}'.format(20))
20
>>> print('{:o}'.format(20))
24
>>> print('{:x}'.format(20))
14
>>> print('{:e}'.format(20))
2.000000e+01
>>> print('{:g}'.format(20.1))
20.1
>>> print('{:f}'.format(20))
20.000000
>>> print('{:n}'.format(20))
20
>>> print('{:%}'.format(20))
2000.000000%
>>>


3.进制转换
>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)     # 在前面加“#”,则带进制前缀
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

4.百分数%
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'


5.正负符号显示
>>> '{:+f}; {:+f}'.format(3.14, -3.14)     # 总是显示符号
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14)     # 若是+数,则在前面留空格
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)     # -数时显示-,与'{:f}; {:f}'一致
'3.140000; -3.140000'

6.时间
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'


7.format的用法变形
# a.format(b)
>>> "{0} {1}".format("hello","world")
'hello world'


# f"xxxx"# 可在字符串前加f以达到格式化的目的,在{}里加入对象,此为format的另一种形式:
>>> a = "hello"
>>> b = "world"
>>> f"{a} {b}"
'hello world'



name = 'jack'
age = 18
sex = 'man'
job = "IT"
salary = 9999.99

print(f'my name is {name.capitalize()}.')
print(f'I am {age:*^10} years old.')
print(f'I am a {sex}')
print(f'My salary is {salary:10.3f}')

# 结果
my name is Jack.
I am ****18**** years old.
I am a man
My salary is   9999.990


原文链接:https://blog.csdn.net/qq_22613769/article/details/107953257
  • 6
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值