-1

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.

CreepyRaccoon
  • 826
  • 1
  • 9
  • 19
Tor O
  • 51
  • 8
  • Does this answer your question? [How to escape curly-brackets in f-strings?](https://stackoverflow.com/questions/42521230/how-to-escape-curly-brackets-in-f-strings). In summary, you have to use 2 brackets instead of one. – Karolis Nov 18 '22 at 14:13
  • `test[i] = f"({values[i]})"` you can use list indexing (or pretty much any python expression) in an f string. The contents of the string have nothing to do with how you insert it into an fstring. – Pranav Hosangadi Nov 18 '22 at 14:25

1 Answers1

0

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.

CreepyRaccoon
  • 826
  • 1
  • 9
  • 19