Python f-strings with Examples

Python f string examples: PEP 498 created a new string formatting mechanism known as Literal String Interpolation, or F-strings (because of the leading f character preceding the string literal). The goal of f-strings is to make string interpolation easier.

Prefix the string with the letter ” f ” to make an f-string. The string itself can be formatted in the same way that str.format() does. f-strings are a simple and convenient approach to format python expressions by embedding them inside string literals.

Requirement for f-strings in Python:

Python f string example: The Python f-string is mostly used for string formatting. Prior to the advent of “f-strings,” we had the following methods for formatting strings in Python:

1) ‘%’ Operator:

The Python percentile(%) operator is incompatible with Objects and attributes. It cannot be used with objects and attributes. This is the main disadvantage of it.

2)format() Method:

Although the string.format() function was able to overcome the disadvantage of the ‘%’ operator, it proved to be a lengthy method of formatting. This is the main disadvantage of the format() method.

As a result, Python f-strings were created, allowing strings to be interpolated and formatted with considerably simpler and minimum syntax. The Python interpreter formats the strings at runtime.

f-strings with Examples

The f-string, also known as formatted strings, is used for Literal String Interpolation, which is the injection of strings and formatting of the specified string.

Syntax:

f '{string}'

Example

Approach:

  • Give the first string as static input and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Format the given two strings using ‘f’ as the preceding character (f-string).
  • Store it in another variable.
  • Print the above-obtained formatted string.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as static input and store it in a variable.
gvn_fststr = 'Btechgeeks'
# Give the second string as static input and store it in another variable.
gvn_scndstr = 'Hello'
# Format the given two strings using 'f' as the preceding character(f-string).
# Store it in another variable.
rslt_str = f'{gvn_scndstr} this is {gvn_fststr}'
# Print the above-obtained formatted string
print("The above-obtained formatted string is:\n", rslt_str)

Output:

The above-obtained formatted string is:
 Hello this is Btechgeeks

Here, f-string is used to inject or interpolate the input strings gvn_fststr and gvn_scndstr between string statements.

f-strings with Raw Strings:

Python raw strings treat special characters known as ‘escape sequences’ as literal characters. It is utilized when we wish escape sequences, such as ‘\n’ or backslash(\), to be literal sequences of characters.

Syntax: (raw string)

r 'string'

Python f-strings can be used simultaneously with raw strings.

Syntax: (f-strings with Raw Strings)

fr 'string or {string}'

Example

# Give the first string as static input and store it in a variable.
gvn_fststr = 'Btechgeeks'
# Give the second string as static input and store it in another variable.
gvn_scndstr = 'Hello'
# Format the given two strings using 'fr' as the preceding characters(f-string with
# the raw-string).
# Store it in another variable.
rslt_str = fr'{gvn_scndstr}\n this is {gvn_fststr}'
# Print the above-obtained formatted string
print("The above-obtained formatted string is:\n", rslt_str)

Output:

The above-obtained formatted string is:
 Hello\n this is Btechgeeks

Explanation:

Here, '\n' is considered as a literal character.

Functions Calling Using f-string

Python f-strings allow us to call functions from within them. As a result, the code has been optimized to some extent. A similar method can be used to create lambda functions inside f-string braces.

Syntax:

f'{func()}'

Example

Approach:

  • Create a function say ‘addition’ which accepts two numbers as the argument and returns the addition of two numbers.
  • Inside the function add both the given numbers and store it in a variable.
  • Return the above result i.e, the sum of both the given numbers.
  • Pass two random numbers to the above-created function ‘addition’ with ‘f’ as the preceding character.
  • Store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Create a function say addition which accepts two numbers as the argument and
# returns the addition of two numbers.


def addition(num_1, num_2):
    # Inside the function add both the given numbers and store it in a variable.
    rsltsum = num_1+num_2
    # Return the above result i.e, the sum of both the given numbers.
    return rsltsum


# Pass two random numbers to the above-created function 'addition' with 'f'
# as the preceding character.
# Store it in another variable.
addtn_rslt = f'{addition(30,40)}'
# Print the above result.
print("The sum of given two numbers = ", addtn_rslt)

Output:

The sum of given two numbers =  70

f-string in Python with blank or white-spaces

The f-strings in python can also work with whitespaces and blanks. The trailing and leading white spaces are ignored, and the spaces between the literal string are unchanged.

Example

addtn_rslt = f'  The sum of given two numbers: { 30 + 40 }  '
print(addtn_rslt)

Output:

The sum of given two numbers: 70

f-string in Python with Expressions

Expressions can be used with Python f-string. As a result, simple modifications can be carried out directly within the f-string.

Syntax:

f '{expression}'

Example

# Give the first number as static input and store it in a variable.
num_1 = 50
# Give the second number as static input and store it in another variable.
num_2 = 30
# Using f-string with the expression and printing it
print(f'The sum of 30 and 50 = {num_1+num_2}')

Output:

The sum of 30 and 50 = 80

f-string in Python with Dictionary

The Python dictionary data structure operates with key-value pairs. Along with the dictionaries, Python f-strings can be framed.

Syntax:

f"{dictionary['key']}"

Example

# Give the dictionary as static input and store it in a variable.
gvn_dictnry = {'hello': 100, 'btechgeeks': 200}
# Print the value of the key of the dictionary(btechgeeks) using the f-string
print(f"{gvn_dictnry['btechgeeks']}")

Output:

200