【问题标题】:What is print(f"...")什么是 print(f"...")
【发布时间】:2019-11-30 16:33:00
【问题描述】:

我正在阅读一个接受 XML 文件输入并输出 XML 文件的 python 脚本。但是,我不明白打印语法。有人能解释一下print(f"...") 中的f 是做什么的吗?

args = parser.parser_args()

print(f"Input directory: {args.input_directory}")
print(f"Output directory: {args.output_directory}")

【问题讨论】:

标签: python


【解决方案1】:

在 Python 3.6 中,引入了 f-string (PEP 498)。简而言之,这是一种更易读、更快速的字符串格式化方式。

例子:

agent_name = 'James Bond'
kill_count = 9

# old ways
print('{0} has killed {1} enemies '.format(agent_name,kill_count))

# f-strings way
print(f'{agent_name} has killed {kill_count} enemies')

字符串前面的 fF 告诉 Python 查看 {} 中的值,如果存在则用变量值替换它们。 f 格式的最大优点是您可以在 {} 中做一些很酷的事情,例如{kill_count * 100}.

您可以使用它来使用 print 进行调试,例如

print(f'the {agent_name=}.')
# the agent_name='James Bond'

格式化,例如零填充、浮点数和百分比舍入变得更容易:

print(f'{agent_name} shoot with {9/11 : .2f} or {9/11: .1%} accuracy')
# James Bond shoot with  0.82 or  81.8% accuracy 

还有更多。读数:

【讨论】:

    【解决方案2】:

    'f''F'为前缀的字符串并将表达式写成{expression}是一种格式化字符串的方法,其中可以包含Python表达式的值。

    以这些代码为例:

    def area(length, width):
        return length * width
    
    l = 4
    w = 5
    
    print("length =", l, "width =", w, "area =", area(l, w))  # normal way
    print(f"length = {l} width = {w} area = {area(l,w)}")     # Same output as above
    print("length = {l} width = {w} area = {area(l,w)}")      # without f prefixed
    

    输出:

    length = 4 width = 5 area = 20
    length = 4 width = 5 area = 20
    length = {l} width = {w} area = {area(l,w)}
    

    【讨论】:

      【解决方案3】:

      python 中的 f-string 允许您使用字符串模板格式化数据以进行打印。
      下面的例子将帮助你澄清

      使用 f-string

      name = 'Niroshan'
      age  = 25;
      print(f"Hello I'm {name} and {age} years young")
      

      你好,我是 Niroshan,25 岁​​


      没有 f-string

      name = 'Niroshan'
      age  = 25;
      print("Hello I'm {name} and {age} years young")
      

      您好,我是 {name},年轻 {age} 岁

      【讨论】:

        【解决方案4】:

        f 字符串也称为字面量字符串,用于在字符串中插入一个变量并使其成为一部分,而不是这样做

        x = 12
        y = 10
        
        word_string = x + ' plus ' + y + 'equals: ' + (x+y)
        

        相反,你可以这样做

        x = 12
        y = 10
        
        word_string = f'{x} plus {y} equals: {x+y}'
        output: 12 plus 10 equals: 22
        

        这也将有助于间距,因为它会完全按照字符串的写入方式进行

        【讨论】:

        • 第 2 日的结束语少了一个 word_string
        【解决方案5】:
        args = parser.parser_args()
        
        print(f"Input directory: {args.input_directory}")
        print(f"Output directory: {args.output_directory}")
        

        相同
        print("Input directory: {}".format(args.input_directory))
        print("Output directory: {}".format(args.output_directory))
        

        也一样

        print("Input directory: "+args.input_directory)
        print("Output directory: "+args.output_directory)
        

        【讨论】:

        • 请注意,严格来说,这三种技术是不等价的。它们各自具有不同的性能特征,并且在处理非字符串参数的方式上也各不相同。
        【解决方案6】:

        f 表示 Formatted string literals,它是 Python 3.6 中的新词。


        格式化字符串文字f-string是一个字符串文字,它是 前缀为'f''F'。这些字符串可能包含替换 字段,它们是由大括号 {} 分隔的表达式。尽管 其他字符串文字总是有一个常量值,格式化字符串 实际上是在运行时计算的表达式。


        格式化字符串文字的一些示例:

        >>> name = "Fred"
        >>> f"He said his name is {name}."
        "He said his name is Fred."
        
        >>> name = "Fred"
        >>> f"He said his name is {name!r}."
        "He said his name is Fred."
        
        >>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
        "He said his name is Fred."
        
        >>> width = 10
        >>> precision = 4
        >>> value = decimal.Decimal("12.34567")
        >>> f"result: {value:{width}.{precision}}" # nested fields
        result: 12.35
        
        >>> today = datetime(year=2017, month=1, day=27)
        >>> f"{today:%B %d, %Y}" # using date format specifier
        January 27, 2017
        
        >>> number = 1024
        >>> f"{number:#0x}" # using integer format specifier
        0x400
        

        【讨论】:

        • python新手:The repr() function returns a printable representational string of the given object.
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-02
        • 2020-02-08
        • 2011-07-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多