snippetpythonTip
2 ways to format a string in Python
Viewed 0 times
pythonformatwaysstring
Problem
Formatted string literals, commonly known as f-strings, are strings prefixed with
The
'f' or 'F'. These strings can contain replacement fields, enclosed in curly braces ({}).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.Solution
name = 'John'
age = 32
print(f'{name} is {age} years old') # 'John is 32 years old'Code Snippets
name = 'John'
age = 32
print(f'{name} is {age} years old') # 'John is 32 years old'name = 'John'
age = 32
print('{0} is {1} years old'.format(name, age)) # 'John is 32 years old'Context
From 30-seconds-of-code: fstrings-str-format
Revisions (0)
No revisions yet.