Formatted String in Python

Formatted string in Python

Formatted string or F-string in Python makes it possible to format strings this way:

name = "Nick"
print(f"My name is {name}")

Output:

My name is Nick

As opposed to the old-school approach using the format() method:

name = "Nick"
print("My name is {}".format(name))

The f-string approach is more convenient especially when the number of embedded variables is big.

Notice that f-strings became available in Python 3.6.

Formatted Strings in Python—The Old Way

Ever since Python 2.6, you have probably used the format() method to format strings. As an example:

name = "Nick"
print("My name is {}".format(name))

Output:

My name is Nick

However, If you increase the number of variables the code becomes pretty messy.

For instance, take a look at this:

first_name = "Nick"
last_name = "Jones"
profession = "Software Engineer"
platform = "Codingem"

print("Hi! I am {first_name} {last_name}, a {profession}. I'm writing a new article on{platform}.".format(first_name= first_name, last_name =last_name , profession = profession, platform = platform))

Output:

Hi! I am Nick Jones, a Software Engineer. I'm writing a new article on Codingem.com.

As you can see, the code that produces this sentence gets quite verbose with long string formatting chains.

But this is where the f-strings save the day.

F-Strings or Formatted Strings to the Rescue

Due to the messy string formatting with format() method, Python 3.6 introduces a more concise way to format strings.

The new-school way is known as f-strings.

Using an f-string is easy:

  • Add character f in front of a string.
  • Inside the string add any number of variables wrapped around curly braces {}.

For example:

name = "Nick"
print(f"My name is {name}")

Output:

My name is Nick

Let’s repeat the example with multiple variables using an f-string this time:

first_name = "Nick"
last_name = "Jones"
profession = "Software Engineer"
platform = "Codingem.com"

print(f"Hi! I am {first_name} {last_name}, a {profession}. I'm writing a new article on {platform}.")

Output:

Hi! I am Nick Jones, a Software Engineer. I'm writing a new article on Codingem.com.

Looks better now, doesn’t it? There are no long .format() chains needed anymore.

Next, let’s take a look at how to do some basic formatting with f-strings.

Arbitrary Expressions and Formatted Strings

You can add any valid Python expression inside of an f-string.

For example, let’s do some maths:

print(f"The result of 3*6 is {3*6}")

Output:

The result of 3*6 is 18

Multi-Line Formatted Strings in Python

To further improve code readability you may introduce line breaks in longer f-strings.

As an example:

first_name = "Nick"
last_name = "Jones"
profession = "Software Engineer"
platform = "Codingem"

message = (
    f"Hi! I am {first_name} {last_name}."
    f"I'm a {profession}."
    f"I'm writing a new article on{platform}."
)

print(message)

Format Data Like a Table Using Formatted Strings

You can specify the number of spaces taken by each variable inside your f-string.

For instance, let’s make number data look like a table:

data = [("x", "y", "sum"), (1, 2, 3), (3, 5, 8)]

for x,y,sum in data:
    print(f"{x:{1}} {y:{1}} {sum:{2}}")

Result:

x y sum
1 2  3
3 5  8

Control the Number of Decimal Places with F-Strings

To determine the precision of for example a float, you can use a colon followed by the number of digits you need.

For instance, let’s print a float with 2 decimal accuracy using an f-string:

f_num = 12.3241233
print(f"The number is: {f_num:.2f}")

Output:

The number is: 12.32

Conclusion

Formatted string in Python is a new feature in Python 3.6. It lets you format strings like this:

name = "Nick"
print(f"My name is {name}")


The benefit of f-strings over the old-school format() method becomes imminent when dealing with multiple variables: Using format() makes the code look ugly. With f-strings you just write the variable where you want it to appear and that’s it.

Thanks for reading. I hope you find it useful.

Happy coding!

You Might Find Insightful

10 Useful Python Snippets to Code Like a Pro

Web Development Buzzwords in 2021

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *