Python - 使用变量作为字符串格式化的一部分

sha*_*fuq 7 python string-formatting

我搜索了一个答案,但因为它有点具体无法找到答案.专家的一个简单问题(我希望).

我希望能够使用int变量而不是下面代码中使用的数字(5).我希望有一种方法,否则我将把我的代码放在if块中,如果可能的话我试图避免(我不希望它在我的循环中每次都经历一个条件).

my_array[1, 0] = '{0:.5f}'.format(a)
Run Code Online (Sandbox Code Playgroud)

有没有办法让我使用如下变量编写下面的代码:

x = 5
my_array[1, 0] = '{0:.xf}'.format(a)
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

Ev.*_*nis 17

当然有:

x = 5
a = '{1:.{0}f}'.format(x, 1.12345111)
print(a)  # -> 1.12345
Run Code Online (Sandbox Code Playgroud)

如果您不想指定位置(0&1),则只需反转输入:

a = '{:.{}f}'.format(1.12345111, x)
#                    ^ the float that is to be formatted goes first
Run Code Online (Sandbox Code Playgroud)

这是因为第一个参数,以format()进入到 第一(最外)托架的字符串.

结果,以下失败:

a = '{:.{}f}'.format(x, 1.12345111) 
Run Code Online (Sandbox Code Playgroud)

因为{:1.12345111f}无效.


格式化的其他示例您可能会感兴趣:

a = '{:.{}{}}'.format(1.12345111, x, 'f')  # -> 1.12345

a = '{:.{}{}}'.format(1.12345111, x, '%')  # -> 112.34511%

a = '{:.{}}'.format(1.12345111, '{}{}'.format(x, 'f'))  # -> 112.34511%
Run Code Online (Sandbox Code Playgroud)

最后,正如@m_____z在他的答案中指出的那样,如果你使用的是Python3.6或更高版本,你可以通过使用来轻松完成所有这些工作f-strings.

x = 5
a = '{1:.{0}f}'.format(x, 1.12345111)
print(a)  # -> 1.12345
Run Code Online (Sandbox Code Playgroud)

注意0引号之前.


m__*_*__z 7

假设您使用的是Python 3.6,您可以简单地执行以下操作:

x = 5
my_array[1, 0] = f'{a:.{x}f}'
Run Code Online (Sandbox Code Playgroud)