What is the name of this structure in Python?

Asked

Viewed 111 times

10

In the following code:

first_part = 46
last_part = 57
guess = f'{first_part}{last_part}'.encode()

print(guess)
print(type(guess))

But I didn’t understand the code:

guess = f'{first_part}{last_part}'.encode()

I need an explanation or the name of this structure so I can study.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

2 answers

11

This is called informally f-strings, but the more formal term is interpolation literal of strings. The f there indicates that the following text is a feedback of what will be used, so within it there will be normal text and code that will generate a part of the final text, ie there will be execution of what is inside. The parts that will be executed are between keys. Then in this case you will print 4657 because the indication is that you want these values printed one after the other. The part of the code is the one between keys.

  • Thank you very much!

8

Is known for f-string, a new syntax added to Python in version 3.6 to perform interpolation of strings. It must necessarily have the prefix f and all groups between keys, {var}, shall be analysed and replaced by the respective variable values, var.

In your case, the value of guess will be the string '4657', for {first_part} shall be assessed at 46 and {last_part} as 57, making the interpolation.

  • Thank you very much!

Browser other questions tagged

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