String Formatting - Advanced Operations for Dicts, Lists, Numbers, and Dates

String Formating - Dicts, List

person = {"name":"dale","age":"25"}
  • placeholder 和 format中的参数一一对应。
"my name is {0} and i am {1} years old.".format(person["name"],person["age"])
'my name is dale and i am 25 years old.'

花括号中的位置参数也可以省略,如果是按照顺序对应的话

"my name is {} and i am {} years old.".format(person["name"],person["age"]) 
'my name is dale and i am 25 years old.'
  • 也可以这样,format中的两个参数,对应多个花括号位置
tag = "h1"
text = "this is h1"
"<{0}>{1}</{0}>".format(tag,text)
'<h1>this is h1</h1>'
  • dict可以这样对应
"my name is {0[name]} and i am {0[age]} years old.".format(person)
'my name is dale and i am 25 years old.'
  • list可以这样对应
list1 = ["dale","23"]
"my name is {0[0]} and i am {0[1]} years old.".format(list1)
'my name is dale and i am 23 years old.'
  • 实例化的对象属性可以这样对应
class Person:
    def __init__(self,name,age):
        self.name = name 
        self.age = age
p1= Person("dale","25")
"my name is {0.name} and i am {0.age} years old.".format(p1)
'my name is dale and i am 25 years old.'
  • format中以参数对传入

这种形式更加便于代码的阅读,可读性高

"my name is {name} and i am {age} years old.".format(name = "dale",age = "25") # for parameter dict, this is a more readable way
'my name is dale and i am 25 years old.'
person = {"name":"dale","age":"25"}

相当于unpack了person字典,然后以参数对的形式传递参数(类似上面的这样形式)

"my name is {name} and i am {age} years old.".format(**person) # **dict, uppack a dict, 变成上面的这种形式
'my name is dale and i am 25 years old.'

String Formating - Numbers

  • :符号后面的内容为显示设定格式
for i in range(1,11):
    print("the value is {:02}".format(i)) # 02 表示以两位数字显示
the value is 01
the value is 02
the value is 03
the value is 04
the value is 05
the value is 06
the value is 07
the value is 08
the value is 09
the value is 10

03 表示以三位数字显示

for i in range(1,11):
    print("the value is {:03}".format(i))
the value is 001
the value is 002
the value is 003
the value is 004
the value is 005
the value is 006
the value is 007
the value is 008
the value is 009
the value is 010
  • .2f 确定小数点后的位数
pi = 3.1415926
"Pi is equal to {:.2f}".format(pi)
'Pi is equal to 3.14'
  • :,
"1 MB is equal to {:,} bytes".format(1000**2)
'1 MB is equal to 1,000,000 bytes'
"1 MB is equal to {:,.2f} bytes".format(1000*2)
'1 MB is equal to 2,000.00 bytes'

String Formating - Dates

import datetime
mydate = datetime.datetime(2019,2,1,12,30,45)
print(mydate)
2019-02-01 12:30:45
"{:%B %d, %Y}".format(mydate)
'February 01, 2019'
"{0:%B %d,%Y} fell on a {0:%A} and was the {0:%j} day of the year.".format(mydate)
'February 01,2019 fell on a Friday and was the 032 day of the year.'

引用

本文主要参考下列视频内容,翻译并亲测代码后形成此文,感谢视频作者的无私奉献!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值