What is the name of this structure in Python?

9

In the following code:

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

print(guess)
print(type(guess))

But I did not understand the code snippet:

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

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

    
asked by anonymous 27.09.2018 / 15:20

2 answers

10

This is called informally f-strings , but the more formal term is interpolation literal of strings . The% with% there indicates that the following text is a template of what will be used, then inside 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 therein. The parts they will execute are in braces. Then in this case it will print f because the indication is that it wants these values printed one next to the other. The code part is what's in the braces.

    
27.09.2018 / 15:28
8

It is known as 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 the groups in braces, {var} , will be parsed and replaced by the values of the respective variables, var .

In your case, the value of guess will be the string '4657' , because {first_part} will be evaluated as 46 and {last_part} as 57, doing the interpolation.

27.09.2018 / 15:27