python format 高级用法_Python format的用法

本文详细讲解了Python中的字符串格式化技巧,包括位置info、下标、关键字参数、高级类Person的实例,以及格式控制如对齐、进制转换、精度调整、日期格式等。涵盖了基础到进阶的实用技巧,并展示了在实际场景中的应用。
摘要由CSDN通过智能技术生成

普通使用

# 通过位置

info1 = '{}, {}'.format('Gage', 25) # Gage,25

info2 = '{1}, {1}'.format('Gage', 25) # 25,25

# 通过下标(列表)

p = ('Gage', 25)

print('{0[0]}'.format(p)) # Gage

print('{0[0]}, {0[1]}'.format(p)) # Gage,25

# 通过关键字参数

print('{name}, {age}'.format(name="Gage", age=25)) # Gage 25

print('{[name]}'.format(dict(name="I'm Gage"))) # I'm Gage

# 元组和字典info = ('Ggae', 25)

site = {'company': 'xitucheng', 'home': 'zhuxinzhuang'}

print("I'm {0}, {1} years old, working in {company}.".format(*info, **site)) # I'm Ggae, 25 years old, working in xitucheng.

高级使用

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

def __str__(self):

return "This boy is {self.name}, {self.age} years old.".format(self=self)

p = Person('Gage', 25)print(p)

进阶使用

# 填充和对齐

1、^、<、>分别是居中、左对齐、右对齐,后面带宽度

2、:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充

print('{:t>8}'.format(189)) # ttttt189

print('{:t<8}'.format(189)) # 189ttttt

print('{:t^8}'.format(189)) # tt189ttt

# 进制转换

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

print('{:b}'.format(10)) # 1010

print('{:d}'.format(10)) # 10

print('{:o}'.format(10)) # 12

print('{:x}'.format(10)) # a

# 精度转换

print('{:.2f}'.format(3.1415926)) # 3.14

# 科学计数法

print('{:8e}'.format(189)) # 1.890000e+02

# 金额分割

print('{:,d}'.format(1234567890)) # 1,234,567,890

# 百分比print('{:%}'.format(0.314)) # 31.400000%

# 日期格式自定义

from datetime import datetime

print("Today is: {0:%a %b %d %H:%M:%S %Y}".format(datetime.now())) # Today is: Tue Jun 11 17:21:15 2019

免责声明:内容和图片源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值