Python From Beginner to Advanced

0% completed

Previous
Next
String Formatting in Python

String formatting allows for creating more dynamic and readable strings by inserting variables or expressions inside string templates. Python provides multiple ways to format strings, including the older % formatting, the str.format() method, and the modern f-strings introduced in Python 3.6.

1. Using f-strings (Recommended)

F-strings (formatted string literals) are the most concise and readable way to format strings in Python. They allow variables and expressions to be embedded directly within string literals using {}.

Example 1: Using f-strings

Python3
Python3

. . . .

Explanation

  • The f before the string enables formatted string literals.
  • Variables name and age are directly inserted into the string using {}.
  • This method improves readability and eliminates the need for additional formatting functions.

Example 2: Performing Calculations in f-strings

Python3
Python3

. . . .
  • Expressions inside {} are evaluated directly within the string.

2. Using "str.format()" Method

The format() method was widely used before f-strings and works by placing {} placeholders in the string and passing values as arguments.

Example 3: Using "str.format()"

Python3
Python3

. . . .
  • {} serves as placeholders that get replaced with arguments inside format().

Example 4: Using Named Placeholders

Python3
Python3

. . . .
  • Named placeholders make the format more readable, especially in complex strings.

3. Using "%" Formatting (Old Method)

This method was commonly used in older Python versions but is now less preferred due to readability and flexibility limitations.

Example 5: Using "%" Formatting

Python3
Python3

. . . .
  • %s is a placeholder for strings, and %d is for integers.
  • This method is not recommended as f-strings and format() are more modern and readable.

String formatting helps create dynamic and formatted output efficiently. The recommended approach is f-strings, which are concise, readable, and support inline expressions. The str.format() method is still widely used but requires additional function calls. % formatting is outdated and should be avoided in modern Python programs.

By choosing the right formatting method, you can write cleaner and more maintainable code.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next