python格式化字符串4种方法

1.格式化字符串写法

废话不多说,直接上代码

def str_format():
    context1 = '''there is a person, name: %s, age: %d, salary: %d''' %("lucy", 18, 2000)
    context2 = '''there is a person, name: %(name)s, age: %(age)d, salary: %(salary)d''' %dict(name="lili",age=19, salary=3000)
    context3 = '''there is a person, name: {0}, age: {1}, salary: {2}'''.format("koko", 20, 4000)
    # 3.6以后的版本,推荐使用
    name, age, salary = "hanmeimei", 16, 6000
    context4 = f'''there is a person, name is {name}, age is: {age}, salary is: {salary}'''

    print(context1)
    print(context2)
    print(context3)
    print(context4)

代码输出

there is a person, name: lucy, age: 18, salary: 2000
there is a person, name: lili, age: 19, salary: 3000
there is a person, name: koko, age: 20, salary: 4000
there is a person, name is hanmeimei, age is: 16, salary is: 6000

f-string, formatted string literals,是python 3.6以后引入的操作。在此之前,格式化字符串常用的方法为%格式化与str.format()的方法。

而采用f-string方法,好处主要如下:
1.操作更加直观:{}标明直接被替换的变量。
2.操作更加简单:直接在字符串前面加上f即可。
3.性能也要更优于传统的格式化方法。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值