SoFunction
Updated on 2025-03-02

Example of specific usage of print(f'') in python

Preface

In Python, print(f'') is the syntax for formatting strings (f-string), which allows you to embed expressions in strings that are replaced by their values ​​at runtime. The f or F prefix means that this is a formatted string literal. Inside braces {} in f'' or F'', you can put any valid Python expression. When the print function is executed, these expressions are evaluated and the result is inserted into the corresponding position of the string.

Here are some usesprint(f'')Example:

Example 1: Basic usage

name = "Alice"
print(f"Hello, {name}!") # Output:Hello, Alice!

Example 2: Arithmetic operation

x = 5
y = 10
print(f"The sum of {x} and {y} is {x + y}.") # Output:The sum of 5 and 10 is 15.

Example 3: Accessing dictionary elements

person = {"name": "Bob", "age": 30}
print(f"{person['name']} is {person['age']} years old.") # Output:Bob is 30 years old.

Example 4: Using functions

def square(x):
        return x ** 2
        
number = 4
print(f"The square of {number} is {square(number)}.") # Output:The square of 4 is 16.

Example 5: Format numbers (usually used to retain the decimal places of floating point numbers.)

pi = 3.141592653589793
print(f"The value of pi is approximately {pi:.2f}.") # Output:The value of pi is approximately 3.14.

In the last example above,:.2fis a format specifier that tells Python to convert floating point numberspiFormatted as a string with two decimals.

Format strings provide a concise and readable way to interpolate and format strings, especially when you need to embed variables or perform simple calculations. With traditional string formatting methods (e.g.%operator or()Compared with method), f-string is usually more intuitive and convenient.

Attachment: Floating point output format

Code example:

a = 3.141592654
b = 12.138
print(a)
print(b)
print(f"Pi ≈ {a}")
print("%f" % a)
print("%f" % b)

3.141592654
12.138
Pi ≈ 3.141592654
3.141593
12.138000

When using print only to output floating point numbers with more than six decimal places, the value will not be changed.

You can refer to the first three print functions

When using %f to specify output, it will automatically default to six decimal places

i) If it is insufficient, add 0 until six decimal places are filled

ii) If more than six decimal places are exceeded, the rounding strategy will be used

Summarize

This is the end of this article about the specific usage examples of print(f'') in python. For more related usage content of python print(f'') please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!