Textlogo_codingem_white

Programming tips for everyone

Formatted String in Python

F-string or formatted string in Python makes it possible to format strings like this:

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

Output:

My name is Artturi


As opposed to the old-school approach:

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


The f-string approach is more convenient especially when the number of embedded variables is big. F-strings became available in Python 3.6.


The Old-School Way

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

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


Output:

My name is Artturi


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

first_name = "Artturi"
last_name = "Jalli"
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))


As you can see, the code gets rather verbose real quick.

F-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 simple:

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


For example:

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


Output:

My name is Artturi


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

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


Looks better now, doesn’t it? There’s no infinitely long .format() chain anymore.

Congrats! Now you know what F-strings are and how to use them + why such a gadget was added to Python 3.6. Next, let’s take a look at how to do some basic formatting with f-strings.

Arbitrary Expressions

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 F-Strings

To futher improve code readability you may introduce line breaks in longer f-strings. As an example:

first_name = "Artturi"
last_name = "Jalli"
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 Like a Table

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

To determine the precision of e.g. a float, you can use 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 = "Artturi"
print(f"My name is {name}")


The benefit of f-strings over the old-school format() method becomes eminent 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

Share on facebook
Share on twitter
Share on linkedin

Related Articles

Artturi Jalli

Technical Writer

Entrepreneur, Software Engineer, Mobile App Dev, MSc Physics Student, And Tech Enthusiast from Finland

artturi@codingem.com

My Personal Favorites
Sponsor

Buy an Online Course

Lorem ipsum dolor sit amet consectetur adipiscing elit dolor
Explore Categories

Web Development