I would like to know what is the function of: {} in the Python language and more specifically within the PRINT function as in this code?

Asked

Viewed 1,401 times

3

I would like to know what the function of: {} in the Python language and more specifically within the function PRINT as in this code?

Salario = int(input('Salario? '))
imposto = 27.
while imposto >0.:
    imposto = input('Imposto ou (0) para sair: ')
    if not imposto:
            imposto = 27.
    else:
            imposto=float(imposto)
    print("Valor Real: {0}".format(Salario-(Salario*(imposto*0.01))))

3 answers

8

The {0} means the position of replacing that placeholder with a value or variable. The idea is to act as a mask. Such a type of construction avoids over-concatenations.

format() reminds the function printf() php, where placeholders are defined (in this case {0},{n}) and what the values will be; their order must be respected, otherwise an unexpected result/output will happen.

Example taken from documentation:

>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam

Recommended reading:

Format signature()

2

This is a kind of Python formatting, it replaces the {0} in this case, by the data of the .format(). But there is a more basic one that you can easily replace...

Shape using the . format

nome = input("Escreva seu nome: ")
idade = input('{0}, agora escreva sua idade: '.format(nome))

print('{0}, {1} - Identidade criada'.format(nome, idade))

But there is also a better and easier way to understand visually...

Form "better"

nome = input("Escreva seu nome: ")
idade = input(f'{nome}, agora escreva sua idade: ')

print(f'{nome}, {idade} - Identidade criada')

I consider it better, as it is easier to read by other programmers, decreases the line of code. In this case the f before quotation marks, replaces .format()

0

Browser other questions tagged

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