The Power and Flexibility of F-String

PythonPythonBeginner
Practice Now

Introduction

In this tutorial, you will learn about Python F-strings, a modern and concise way to format strings in Python. F-strings were introduced in Python 3.6 and have quickly become popular among Python developers for their readability and ease of use.

F-strings, also known as "formatted string literals", are a convenient way to embed expressions inside string literals. The expressions are enclosed in curly braces {} and are evaluated at runtime, then formatted and substituted into the resulting string.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-7847{{"`The Power and Flexibility of F-String`"}} python/with_statement -.-> lab-7847{{"`The Power and Flexibility of F-String`"}} python/dictionaries -.-> lab-7847{{"`The Power and Flexibility of F-String`"}} python/sets -.-> lab-7847{{"`The Power and Flexibility of F-String`"}} python/build_in_functions -.-> lab-7847{{"`The Power and Flexibility of F-String`"}} end

Basic F-String Usage

To create an f-string, simply prefix a string literal with the letter 'f' or 'F':

Open the Python shell by typing the following command in the terminal.

python3

Then, enter the following code.

name = "Alice"
age = 30
print(f"{name} is {age} years old.")

Output:

Alice is 30 years old.

F-String Expressions

You can include any Python expressions inside the curly braces {} of an f-string. The expressions are evaluated and the result is converted to a string and inserted into the f-string.

Here's an example:

x = 10
y = 20
print(f"The sum of {x} and {y} is {x+y}.")

Output:

The sum of 10 and 20 is 30.

F-String Formatting

F-strings support various formatting options, such as padding, alignment, and number formatting. You can use the format specifier syntax inside the curly braces {} after an expression, separated by a colon :.

Padding and Alignment

You can use the format specifier to align and pad the result of an expression:

name = "Alice"
print(f"{name:<10}")  ## Left-align, pad with spaces to a width of 10
print(f"{name:>10}")  ## Right-align, pad with spaces to a width of 10
print(f"{name:^10}")  ## Center-align, pad with spaces to a width of 10

Output:

Alice
     Alice
  Alice

Number Formatting

F-strings also allow you to format numbers using the format specifier:

pi = 3.14159265
print(f"Pi is approximately {pi:.3f}.")  ## Format pi with 3 decimal places

Output:

Pi is approximately 3.142.

F-String Tips and Tricks

Here are some tips and tricks to help you get the most out of f-strings:

Escaping Curly Braces

To include literal curly braces in an f-string, double the curly braces {{ and }}:

print(f"{{Hello}}")

Output:

{Hello}

Multiline F-strings

F-strings can span multiple lines using triple quotes """ or ''':

name = "Alice"
age = 30
print(f"""\
Name: {name}
Age: {age}
""")

Output:

Name: Alice
Age: 30

Nested F-Strings

F-strings can be nested, allowing you to format an expression inside another f-string:

age = 10
name = "Alice"
formatted_name = f"{name},{age}"
print(f"Name: {formatted_name}")

Output:

Name: Alice,10

That's it! Now you have a solid understanding of Python f-strings and can use them to make your code more readable and concise. Happy coding!

Summary

In this tutorial, we've explored the power and flexibility of Python f-strings. They provide an efficient and readable way to format strings and embed expressions directly within string literals. With their support for various formatting options, such as padding, alignment, and number formatting, f-strings have become an essential tool for Python developers.

By mastering f-strings, you'll be able to write more concise and expressive code, improving the readability and maintainability of your projects. Keep practicing and experimenting with different f-string features to become even more proficient in their use. Happy coding!

Other Python Tutorials you may like