Reputation: 11
I want to print the statement:
"{C10} {C20}".format(C10=10, C20=20)
but I want to get the names C10
and C20
from other parts of the code, put them in variables, and then use the .format()
method with these variable names.
I simply tried:
Parameter1 = 'C10'
Parameter2 = 'C20'
"{C10} {C20}".format(Parameter1=10, Parameter2=20)
and I get the KeyError
.
Is there any way I can use do it using variables instead of hard coding the names C10
and C20
directly?
Upvotes: 1
Views: 75
Reputation: 96
str.format
accepts {}
or a index inside the curly braces to assign the provided values as per the given index in the braces and not {variable_name}
You could just do it like this
parameter1 = 10
parameter2 = 20
formatted_string = "{} {}".format(parameter1, parameter2)
(Also the question lacks information required to answer this question)
Upvotes: 0
Reputation: 21
Parameter1 = 'C10'
Parameter2 = 'C20'
print("{C10} {C20}".format_map({Parameter1: 10, Parameter2: 20}))
Upvotes: 2