Python - 使用变量作为字符串格式的一部分
Python - Using a variable as part of string formatting
我希望能够使用 int 变量而不是下面代码中使用的数字 (5)。我希望有办法,否则我将不得不把我的代码放在 if 块中,如果可能的话我会尽量避免(我不希望它每次都经历一个条件我的循环)。
my_array[1, 0] = '{0:.5f}'.format(a)
有没有办法让我使用如下变量编写下面的代码:
x = 5
my_array[1, 0] = '{0:.xf}'.format(a)
当然有:
x = 5
a = '{1:.{0}f}'.format(x, 1.12345111)
print(a) # -> 1.12345
如果您不想指定位置 (0
& 1
),您只需 反转 您的输入:
a = '{:.{}f}'.format(1.12345111, x)
# ^ the float that is to be formatted goes first
这是因为到format()
的第一个参数转到
字符串的第一个(最外层)括号。
因此,以下 失败 :
a = '{:.{}f}'.format(x, 1.12345111)
因为 {: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%
最后,如果你用的是Python3.6,请看优秀的f-strings
answer by .
假设您使用的是 Python 3.6,您可以简单地执行以下操作:
x = 5
my_array[1, 0] = f'{a:.{x}f}'
这可以通过两种方式实现。通过使用 str.format() 或使用 %
其中 a
是您要打印的数字,x
是我们可以做到的小数位数:
str.format:
'{:.{dec_places}f}'.format(a, dec_places=x)
%:
'%.*f' % (x, a)
x=5
f='{0:.'+str(x)+'f}'
my_array[1, 0] = f.format(a)
我希望能够使用 int 变量而不是下面代码中使用的数字 (5)。我希望有办法,否则我将不得不把我的代码放在 if 块中,如果可能的话我会尽量避免(我不希望它每次都经历一个条件我的循环)。
my_array[1, 0] = '{0:.5f}'.format(a)
有没有办法让我使用如下变量编写下面的代码:
x = 5
my_array[1, 0] = '{0:.xf}'.format(a)
当然有:
x = 5
a = '{1:.{0}f}'.format(x, 1.12345111)
print(a) # -> 1.12345
如果您不想指定位置 (0
& 1
),您只需 反转 您的输入:
a = '{:.{}f}'.format(1.12345111, x)
# ^ the float that is to be formatted goes first
这是因为到format()
的第一个参数转到
字符串的第一个(最外层)括号。
因此,以下 失败 :
a = '{:.{}f}'.format(x, 1.12345111)
因为 {: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%
最后,如果你用的是Python3.6,请看优秀的f-strings
answer by
假设您使用的是 Python 3.6,您可以简单地执行以下操作:
x = 5
my_array[1, 0] = f'{a:.{x}f}'
这可以通过两种方式实现。通过使用 str.format() 或使用 %
其中 a
是您要打印的数字,x
是我们可以做到的小数位数:
str.format:
'{:.{dec_places}f}'.format(a, dec_places=x)
%:
'%.*f' % (x, a)
x=5
f='{0:.'+str(x)+'f}'
my_array[1, 0] = f.format(a)