Tarun Maganti
Tarun Maganti

Reputation: 3086

On what parameter does python differentiate between a formatted string and a normal string?

x = f"There are {n} types of people"

print(type(x)==type("HELLO")) #returns True

If the formatted string and a normal string are of same type. How does a function differentiate when to format it or when not to?

My guess is whenever I specify f before a string, the interpreter picks up the value of the variables and formats it then and there and function recieves a formatted string.

Is it a shorthand notation just like lambdas in Java 8?

Upvotes: 4

Views: 76

Answers (3)

Chris
Chris

Reputation: 22963

From PEP 498:

F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values.

(emphasis mine)

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249303

In your example:

x = f"There are {n} types of people"

x is never an f-string, it is simply a regular string, already having had the {n} replaced by the value of the variable n.

An f-string is evaluated syntactically and the resulting object type is str.

Upvotes: 2

Joe
Joe

Reputation: 7131

They are the same type.

n = 5
f"There are {n} types of people"

is just a new nice way to insert variables into a string, introduced in Python 3.6

This could also be written like

n = 5
"There are {:d} types of people".format(n)

Upvotes: 0

Related Questions