当前位置:   article > 正文

python格式化字符串4种方法_python 表达式指令 格式化字符串

python 表达式指令 格式化字符串

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

代码输出

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
  • 1
  • 2
  • 3
  • 4

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/153616
推荐阅读
相关标签
  

闽ICP备14008679号