f‘{}‘-‘%s‘%()-‘{}‘.format()

  • f'{}' Python3.6及以上版本才有,Python3.5及以下版本会出错。

  • '%s'%() 常用格式

  • '{}'.format() {}里面可以带数字也可以不带数字,带数字编号可以调换输出顺序,还可以带关键字。

 

device = torch.device(f'cuda:{opt.local_rank}') #python3.6

device = torch.device('cuda:%s' % (opt.local_rank)) #python3.5

device = torch.device('cuda:{0}'.format(opt.local_rank))

填充和对齐^<>分别表示居中、左对齐、右对齐,后面带宽度

print('{:^30}'.format("zhangsan")) # 居中
print('{:>30}'.format("zhangsan")) # 右对齐
print('{:<30}'.format("zhangsan")) # 左对齐
30:字段长度(最左到最右之间的长度)

 

 精度控制  :.nf

print('{:.2f}'.format(3.14159))
结果:3.14
保留两位小数,两位后四舍五入
>>> print('{} {}'.format('zeruns','blog.zeruns.tech'))  # 不带字段
zeruns blog.zeruns.tech
>>> print('{0} {1}'.format('hello','world'))  # 带数字编号
hello world
>>> print('{1}{0}'.format('blog.zeruns.tech','https://'))
https://blog.zeruns.tech
>>> 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'

#通过下标或key匹配参数
>>> 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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值