0

I have searched a few solution, but it may not apply to our case. Here is a minimal code to illustrate what I was trying to do. How can we make the commented code works? We can use python 3.8+ solutions.

teams_list = ["Man Utd", "Man City", "T Hotspur"]
data = list([[1, 2, 1],
                 [0, 1, 0],
                 [2, 4, 2]])


row_format ="{:>10}" * (len(teams_list) + 1) #this code works

# these codes do not work
#customer_defined_len = 10
#row_format ="{:>customer_defined_len}" * (len(teams_list) + 1)

print(row_format.format("", *teams_list))
for team, row in zip(teams_list, data):
    print(row_format.format(team, *row))
drbombe
  • 609
  • 7
  • 15

1 Answers1

3

One way to do this would be f-strings:

customer_defined_len = 10
row_format = f"{{:>{customer_defined_len}}}" * (len(teams_list) + 1)
print(row_format.format("", *teams_list))
for team, row in zip(teams_list, data):
    print(row_format.format(team, *row))

Note that row_format is a f-string that creates the format-string template, so to avoid interpreting {} within the f-string itself, we duplicate it (ie: {{ ...}})

lonetwin
  • 971
  • 10
  • 17
  • I noticed that you use `f"{{:>{customer_defined_len}}}"`. I tried before using `f"{:>{customer_defined_len}}"` which doesn't work. Can you tell me more why your method? – drbombe Jun 09 '21 at 20:18
  • Wow, this deserves an upvote. Can't believe I was missing the extra braces around the expression.... – Ed- Jun 09 '21 at 20:23
  • 1
    @drbombe your attempt didn't work because the `f-string` was attempting to interpret the ^outer^ `{}`. What you want is for it to leave the outer braces as is (to be interpreted by the following `.format()s`) and instead, just interpret the ^inner^ `{}`. iow, you want to [escape the braces](https://stackoverflow.com/a/5466478/262108). – lonetwin Jun 09 '21 at 20:23