Receive a string and put keys in it

Asked

Viewed 264 times

6

I have a script that receives a string. I need to receive this string and add it to its key ends. I have a problem when placing:

variavel = input('informe um valor')
print(f'{variavel} aqui vem um texto.')

I want the return of function print() these keys appear, without the user having to type them. As above, the variable appears as it was typed by the user.

3 answers

6

Maybe you got confused with f-strings who use this syntax and thought it would put the keys, but it’s just the opposite, they’re special in this mechanism. It is possible to use it and I still got what you want, but it doesn’t seem very convenient (see the other answers).

The simple seems to me the most appropriate, make a simple concatenation:

variavel = input('informe um valor')
print('{' + variavel + '} se quiser pode ter um texto aqui')

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

  • Thank you! That’s right!

5


Within a f-string, the characters { and } serve to indicate that you will use the value of the expression that is between them. If you want the characters themselves { and } be printed, you should write them as {{ and }}. Then it would be:

variavel = input('informe um valor')
print(f'{{{variavel}}} aqui vem um texto.')

The first two {{ are used to print the character {, and the third { is part of the expression {variavel}, which is replaced by the variable value. Then the last two }} are used to print the character }.

If the user type "abc", for example, the output will be:

{abc} aqui vem um texto.

Of course you can also use concatenation, as indicates the another answer.

  • Thanks! I didn’t know that part of f-string.

4

To display the characters { and } literally you will need to "escape" them by adding the same character a second time. That is, to present the value { you need to write {{

Since you still want to use interpolation, you will need to use 3 characters. Your code will look like this:

print(f'{{{variavel}}} aqui vem um texto.')
  • Thanks for your help!

Browser other questions tagged

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