Aditya Tiwari Profile picture
👨‍💻 Learning Machine Learning | Posts about python & ML 🤩 65k+ followers on Insta: https://t.co/kZaBcbHeWY

Feb 20, 2023, 18 tweets

F-strings in Python : The ultimate usage tips ⚡

F-strings in Python are a concise and powerful way to format strings. You can include any valid Python expression inside the curly braces in an f-string.

Thread 🧵

#Python #programming

To use an f-string, just prefix your string with the letter "f".

Here's an example that uses an f-string to format a variable:

#Python
1/16

You can use f-strings to format numbers as well. Here's an example that formats a floating-point number with two decimal places:

2/16 #Python

You can also use f-strings to format dates and times. Here's an example that formats a datetime object:

3/16

F-strings can also include conditional expressions. Here's an example that uses a conditional expression to format a string:

4/16

F-strings also support string interpolation for objects that have a __str__ or __repr__ method. Here's an example that formats a custom object:

5/16

You can use f-strings to format dictionary values as well. Here's an example that formats a dictionary:

6/16

F-strings can also include expressions with function calls. Here's an example that uses the len() function:

7/16

F-strings can also include arithmetic expressions. Here's an example that adds two numbers:

8/16

F-strings can include expressions with ternary operators. Here's an example that uses a ternary operator to format a string based on a boolean value:

9/16

F-strings can include expressions with file I/O. Here's an example that reads a file and formats the contents using an f-string:

10/16

You can use f-strings to format values with custom formatting functions. Here's an example that formats a date using a custom formatting function:

11/16

You can use f-strings to format complex objects like dictionaries with nested keys. Here's an example that formats a nested dictionary:

12/16

You can use f-strings to format and align tabular data. Here's an example that formats tabular data using f-strings:

13/16

Using f-strings to write data to a file with a filename variable:
This example uses an f-string to display the number of bytes that were written to the file, as well as the filename itself.

14/16

With f-strings, you can format strings quickly and easily with a minimum of fuss.

Give them a try and see how they can make your code more concise and readable!

15/16

That's all for this thread. Hope you loved these quick code snippets on f-strings.

If you did, follow me for more snippets on python : @TheGeekyB0y

I post about #Python and #javascript .

Get back to top of the thread :

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling