Files
30-seconds-of-code/blog_posts/python-fstrings-str-format.md
Isabelle Viktoria Maciohsek d4abc910af Fix python code tag
2021-01-09 23:28:19 +02:00

1.2 KiB

title, type, tags, authors, cover, excerpt
title type tags authors cover excerpt
Tip: 2 ways to format a string in Python story python,string maciv blog_images/feathers.jpg Learn two ways to format a string in Python with this quick tip.

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'

Image credit: Maksim Shutov on Unsplash