【Python编程练习】字符串格式化

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {}: 来代替以前的 %

format 函数可以接受不限个参数,位置可以不按顺序。

实例
>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序 
'hello world'  
>>> "{0} {1}".format("hello", "world")  # 设置指定位置 
'hello world'  
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置 
'world hello world'

也可以设置参数:

实例
print("{year}年{month}月".format(year="2021", month="11"))  
# 通过字典设置参数 
date = {"year": "2021", "month": "11"} 
print("{year}年{month}月".format(**date))  
# 通过列表索引设置参数 
date = ['2021', '11'] 
print("{0[0]}年{0[1]}月".format(date)) 

输出结果为:

2021年11月
2021年11月
2021年11月
数字格式化
>>> print("{:.2f}".format(3.1415926))
3.14
>>> print("{:02d}".format(1))
01
>>> print("{:b}".format(100))
1100100
>>> print("{:d}".format(100))
100
>>> print("{:o}".format(100))
144
>>> print("{:x}".format(100))
64

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

编程练习

输出事件日志字符串

输入:name="点击买入按钮",time="2021-11-01 11:11:30"
输出:Event:点击买入按钮,Time:2021-11-01 11:11:30

Python在线编程练习:https://lab.csdn.net/suite_show/164

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值