Reputation: 11
is it possible to concat string when using .format()
?
_NACHKOMMASTELLEN = 3
print(" {0:." + str(_NACHKOMMASTELLEN) + "f}".format(round(V_values[0], _NACHKOMMASTELLEN)), end='')
I get the error:
Single '}' encountered in format string
Upvotes: 1
Views: 951
Reputation: 51683
If you are below 3.6 you can double-format:
_NKS = 3 # shortened for 79 line char limit
V_values = [3.123456789]
print(" {{:.{}f}}".format(_NKS ).format(round(V_values[0], _NKS )))
The first format
puts the 3
inplace of {}
and converts the double {{
and}}
to single {
and }
- the resulting string {:.3f}
is then used for the second format
.
As pointed out by @user2357112 in the comment, format is better then I though. This just works as well:
print(" {:.{}f}".format(round(V_values[0], _NKS ),_NKS ))
Output:
3.123
You do not need to if you already use 3.6 - f-strings deal better with it:
_NACHKOMMASTELLEN = 3
V_values = [3.123456789]
print(f" {round(V_values[0], _NACHKOMMASTELLEN):.{_NACHKOMMASTELLEN}f}")
V_values = [3.1]
print(f" {round(V_values[0], _NACHKOMMASTELLEN):.{_NACHKOMMASTELLEN}f}")
Output:
3.123
3.100
Upvotes: 1
Reputation: 23534
You need to wrap your string in parenthesis:
print((" {0:." + str(_NACHKOMMASTELLEN) + "f}").format(round(V_values[0], _NACHKOMMASTELLEN)), end='')
^ ^
So that " {0:." + str(_NACHKOMMASTELLEN) + "f}"
will be formated instead of "f}"
Upvotes: 1