I have a list of values I want to insert inside the parenthesis in an f-string. The length of the list will be different from time to time, therefore, I will make a string with the correct length for each case. The idea was to create a string of proper length and then insert it into the f-string. This fails because it is read as a string.
Is it other workarounds to get the same result or is it a feature with the f-strings I do not know about? This is my code so far:
values = [['First Name Last name', 20],['First Name Last name', 25],['First Name Last name', 30]]
test = [1]*3
for i in range(3):
val = f'''values[{i}]''' #First create innerpart
test[i] = f'''({{{val}}})''' #Then encapsulate it in curly brackets and paranthesis
insert = ' '.join(test)
f'''Test {insert}'''
The output:
'Test ({values[0]}) ({values[1]}) ({values[2]})'
My desired output:
'Test('First Name Last Name',20) ('First Name Last Name',25) ('First Name Last Name',30)'
I have tried to find ways of escaping the quoting in a string without success.
CodePudding user response:
This simpler approach is what you need:
string = "Test"
for val in values:
string = f"({', '.join(str(elem) for elem in val)}) "
print(string[:-1])
Output:
'Test(First Name Last name, 20) (First Name Last name, 25) (First Name Last name, 30)'
There is no need to escape curly brackets, just concatenate all the elements within each list and format them properly.
CodePudding user response:
Not sure what all those curly braces are doing, but here is a much simpler loop:
values = [['First Name Last name', 20],['First Name Last name', 25],['First Name Last name', 30]]
test = ""
for val in values:
test = f"({val}) "
print(f"Test{test})
This way, you do not have to 'hard-code' the length of the string/values.