Tip: 2 ways to format a string in Python

Python, String · Jun 12, 2021

f-string

Formatted string literals, commonly known as f-strings, are strings prefixed with 'f' or 'F'. These strings can contain replacement fields, enclosed in curly braces ({}).

name = 'John'
age = 32

print(f'{name} is {age} years old') # 'John is 32 years old'

str.format()

The str.format() method works very much alike f-strings, the main difference being that replacement fields are supplied as arguments instead of as part of the string.

name = 'John'
age = 32

print('{0} is {1} years old'.format(name, age)) # 'John is 32 years old'

More like this

  • Tips & Tricks

    A collection of quick tips and tricks to level up your coding skills one step at a time.

    Collection · 53 snippets

  • How do I convert a string to lowercase in Python?

    Learn of the two different way to convert a string to lowercase in Python and understand when you should use each one with this quick guide.

    Python, String · Jun 12, 2021

  • Hex to RGB

    Converts a hexadecimal color code to a tuple of integers corresponding to its RGB components.

    Python, String · Sep 15, 2020

  • RGB to hex

    Converts the values of RGB components to a hexadecimal color code.

    Python, String · Nov 2, 2020