【问题标题】:Rendering number to n variable places将数字渲染到 n 个可变位置
【发布时间】:2019-11-23 03:01:27
【问题描述】:

尝试使用 {:.Nf} 将 pi 打印到输入的小数位

尝试用输入的变量 n 替换变量 N。还将 N 替换为 {} 并将 n 分配给它。还将 n 替换为 {n}。

我确信答案是显而易见的,但我似乎看不到它。

from math import pi

# Example input() statement
n = int(input('Please enter an integer: '))

format_string = '{:.nf}'

# Replace this with your own print statement
print(format_string.format(pi))

期望 pi 到 n 位小数,但它正在返回:

“ValueError:格式说明符缺少精度”

我认为这意味着变量 format_string 的格式不正确。

【问题讨论】:

    标签: python


    【解决方案1】:

    至于您的错误,这是因为 n 不是有效的格式说明符。当然 python 不能知道你的意思是你的局部变量n,所以你必须告诉它。为了使您的代码保持相同的结构,您将需要 2 级格式。比如:

    >>> format_string = '{{:.{n}f}}'.format(n=n)
    >>> print(format_string.format(pi))
    3.14159265
    

    或者简单地说:

    >>> format_string = '{:.{n}f}'
    >>> print(format_string.format(pi, n=n))
    3.14159265
    

    我会亲自摆脱单独的format 变量,并将其直接用作打印中的一个字符串。

    对于n = 8

    1. 使用f-strings:(Python 版本 >= 3.6)
    >>> print(f"{pi:.{n}f}")
    3.14159265
    
    1. 使用format:(Python 版本 >= 2.6)
    >>> print("{pi:.{n}f}".format(pi=pi, n=n))
    3.14159265
    
    1. 使用旧的% formatting:
    >>> print("%.*f" % (n, pi))
    3.14159265
    

    【讨论】:

      【解决方案2】:

      将变量 n 放入格式字符串的一种方法是使用 f 字符串,它是在 Python 3.6 中引入的。 f 字符串允许将n 替换为其当前值。但是,这需要大括号,并且您当前在代码中使用的大括号也将被解释为要替换变量。所以用双括号替换那些括号。

      from math import pi
      
      # Example input() statement
      n = int(input('Please enter an integer: '))
      
      format_string = f'{{:.{n}f}}'
      
      # Replace this with your own print statement
      print(format_string.format(pi))
      

      当我运行它并输入值 10 时,我得到了打印输出

      3.1415926536
      

      如果您运行的是 3.6 之前的 Python 版本,请告诉我,我将向您展示如何使用字符串的 format 方法来获得相同的效果。

      【讨论】:

      • print('{:.{}f}'.format(pi,10)) 用于 Python format_string,就无法将上述格式字符串重用于不同的 n,但您可以使用 print(f'{pi:.{n}f}')
      猜你喜欢
      • 1970-01-01
      • 2018-01-24
      • 2023-03-06
      • 2018-04-29
      • 2020-06-04
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多