Error in string formatting

Asked

Viewed 58 times

-1

I’m trying to personalize the spacing used in one string formatted, center to be very visual between the lines. The program is returning me value error.

Follows the code:

def titulo(msg):
  tam = len(msg) + 4
  print('=' * tam)
  print(f'{msg:^tam}')
  print('=' * tam)

titulo('TRATAMENTO DE ERROS E EXCESSÕES')

Python does not accept an integer variable as a parameter to use for spacing? In this case the variable tam.

What would be the right way to center exactly between the lines, taking into account their size and the message itself.

1 answer

2


If you have a variable in a place that expects a literal needs to say it’s a variable, then just as you say it’s an expression to be interpolated and not a text literal, you have to say it’s an expression, this shape is the use of the keys in that part too, so you can use nested keys:

def titulo(msg):
  tam = len(msg) + 4
  print('=' * tam)
  print(f'{msg:^{tam}}')
  print('=' * tam)

titulo('TRATAMENTO DE ERROS E EXCESSÕES')

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.