My First Post      My Facebook Profile      My MeOnShow Profile      W3LC Facebook Page      Learners Consortium Group      Job Portal      Shopping @Yeyhi.com

Pages










Friday, August 23, 2024

Python's F-String for String Interpolation and Formatting

Interpolating Values and Objects in F-Strings

In latest python, F-strings make the string interpolation process intuitive, quick, and concise. The syntax is similar to what you used with .format(), but it’s less verbose. You only need to start your string literal with a lowercase or uppercase f and then embed your values, objects, or expressions in curly brackets at specific places:

>>> name = "Jane"
>>> age = 25
>>> f"Hello, {name}! You're {age} years old."
'Hello, Jane! You're 25 years old.'

Earlier in Python 3.6 we had the Modulo Operator, % for thsi purpose

The modulo operator (%) was the first tool for string interpolation and formatting in Python and has been in the language since the beginning. Here’s what using this operator looks like in practice:

>>> name = "Jane"
>>> "Hello, %s!" % name
'Hello, Jane!'
Or, see the next example
>>> name = "Jane"
>>> age = 25

>>> "Hello, %s! You're %s years old." % (name, age)
'Hello, Jane! You're 25 years old.'
Or, see the next example for decimal point formatting
>>> "Balance: $%.2f" % 5425.9292
'Balance: $5425.93'

No comments:

Post a Comment