String formatting: % vs. .format vs. string literal

后端 未结 16 2770
青春惊慌失措
青春惊慌失措 2020-11-21 04:18

Python 2.6 introduced the str.format() method with a slightly different syntax from the existing % operator. Which is better and for what situations?

Pyt

16条回答
  •  一整个雨季
    2020-11-21 04:57

    I would add that since version 3.6, we can use fstrings like the following

    foo = "john"
    bar = "smith"
    print(f"My name is {foo} {bar}")
    

    Which give

    My name is john smith

    Everything is converted to strings

    mylist = ["foo", "bar"]
    print(f"mylist = {mylist}")
    

    Result:

    mylist = ['foo', 'bar']

    you can pass function, like in others formats method

    print(f'Hello, here is the date : {time.strftime("%d/%m/%Y")}')
    

    Giving for example

    Hello, here is the date : 16/04/2018

提交回复
热议问题