Python output formats

后端 未结 1 980
执念已碎
执念已碎 2021-01-29 06:46

Hi there I\'ve had a search output formats and formats had no luck. I couldn\'t find right documentation for it and I really want to learn how this code works if somebody could

1条回答
  •  情歌与酒
    2021-01-29 07:23

    Python supports different ways of formatting strings. Unfortunately, they are not all in the same place in the documentation. So, I guess it makes sense to put them all in one SO answer :)

    What you have in the question is printf-style formatting using the modulo (%) operator. For the specification of that see printf-style String Formatting.

    Example:

    x = 9
    print('value of x is %d' % x)
    

    For formatting using the format function, see Format String Syntax.

    Example:

    x = 9
    print('value of x is {x}'.format(x=x))
    

    The same syntax is used as basis for f-strings. See PEP-0498.

    Example:

    x = 9
    print(f'value of x is {x}')
    

    There are also template strings, see Template strings specification. Example:

    x = 9
    print(string.Template('value of x is $x').substitute(x=x))
    

    0 讨论(0)
提交回复
热议问题