Here's what I have as a reference. Basically a summary of the Format Specification Mini-Language . This would all go after a : in the f-string curly braces. So if you want a float with 2 decimal place precision, with * as fill and right aligned in a field width of 10 characters you'd do f"{val:*>10.2f}" [[fill]align][sign][#][0][minimumwidth][.precision][type] Fill: Add a character to fill with. Must be followed by Align flag. Align: '<' - Forces the field to be left-aligned within the available space (This is the default.) '>' - Forces the field to be right-aligned within the available space. '=' - Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form '+000000120'. This alignment option is only valid for numeric types. '^' - Forces the field to be centered within the available space. Sign: '+' - indicates that a sign should be used for both positive as well as negative numbers '-' - indicates that a sign should be used only for negative numbers (this is the default behavior) ' ' - indicates that a leading space should be used on positive numbers #: Flags alternate numbering formats; binary, octal, and hexadecimal output will be prefixed with '0b', '0o', and '0x', respectively. 0: Zero-padding. Equivalent to fill '=' and character of '0' Minimumwidth: Min width of the field. Precision: Decimal places for floats or max field size for non-numeric types. Type: Integers: 'b' - Binary. Outputs the number in base 2. 'c' - Character. Converts the integer to the corresponding Unicode character before printing. 'd' - Decimal Integer. Outputs the number in base 10. 'o' - Octal format. Outputs the number in base 8. 'x' - Hex format. Outputs the number in base 16, using lower- case letters for the digits above 9. 'X' - Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9. 'n' - Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters. '' (None) - the same as 'd' Floats: 'e' - Exponent notation. Prints the number in scientific notation using the letter 'e' to indicate the exponent. 'E' - Exponent notation. Same as 'e' except it converts the number to uppercase. 'f' - Fixed point. Displays the number as a fixed-point number. 'F' - Fixed point. Same as 'f' except it converts the number to uppercase. 'g' - General format. This prints the number as a fixed-point number, unless the number is too large, in which case it switches to 'e' exponent notation. 'G' - General format. Same as 'g' except switches to 'E' if the number gets to large. 'n' - Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters. '%' - Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign. '' (None) - similar to 'g', except that it prints at least one digit after the decimal point. Answer from ebdbbb on reddit.com
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ inputoutput.html
7. Input and Output โ€” Python 3.14.6 documentation
More information can be found in the printf-style String Formatting section. open() returns a file object, and is most commonly used with two positional arguments and one keyword argument: open(filename, mode, encoding=None)
๐ŸŒ
W3Schools
w3schools.com โ€บ PYTHON โ€บ python_string_formatting.asp
Python String Formatting
To specify a string as an f-string, simply put an f in front of the string literal, like this: ... To format values in an f-string, add placeholders {}, a placeholder can contain variables, operations, functions, and modifiers to format the value.
๐ŸŒ
Fstring
fstring.help โ€บ cheat
Python f-string cheat sheet
Type f with precision .n displays n digits after the decimal point. Type g with precision .n displays n significant digits in scientific notation. Trailing zeros are not displayed. ... An empty type is synonymous with d for integers. These format specifications only work on integers (int). ... These format specifications work on strings ...
Top answer
1 of 2
3
Here's what I have as a reference. Basically a summary of the Format Specification Mini-Language . This would all go after a : in the f-string curly braces. So if you want a float with 2 decimal place precision, with * as fill and right aligned in a field width of 10 characters you'd do f"{val:*>10.2f}" [[fill]align][sign][#][0][minimumwidth][.precision][type] Fill: Add a character to fill with. Must be followed by Align flag. Align: '<' - Forces the field to be left-aligned within the available space (This is the default.) '>' - Forces the field to be right-aligned within the available space. '=' - Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form '+000000120'. This alignment option is only valid for numeric types. '^' - Forces the field to be centered within the available space. Sign: '+' - indicates that a sign should be used for both positive as well as negative numbers '-' - indicates that a sign should be used only for negative numbers (this is the default behavior) ' ' - indicates that a leading space should be used on positive numbers #: Flags alternate numbering formats; binary, octal, and hexadecimal output will be prefixed with '0b', '0o', and '0x', respectively. 0: Zero-padding. Equivalent to fill '=' and character of '0' Minimumwidth: Min width of the field. Precision: Decimal places for floats or max field size for non-numeric types. Type: Integers: 'b' - Binary. Outputs the number in base 2. 'c' - Character. Converts the integer to the corresponding Unicode character before printing. 'd' - Decimal Integer. Outputs the number in base 10. 'o' - Octal format. Outputs the number in base 8. 'x' - Hex format. Outputs the number in base 16, using lower- case letters for the digits above 9. 'X' - Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9. 'n' - Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters. '' (None) - the same as 'd' Floats: 'e' - Exponent notation. Prints the number in scientific notation using the letter 'e' to indicate the exponent. 'E' - Exponent notation. Same as 'e' except it converts the number to uppercase. 'f' - Fixed point. Displays the number as a fixed-point number. 'F' - Fixed point. Same as 'f' except it converts the number to uppercase. 'g' - General format. This prints the number as a fixed-point number, unless the number is too large, in which case it switches to 'e' exponent notation. 'G' - General format. Same as 'g' except switches to 'E' if the number gets to large. 'n' - Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters. '%' - Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign. '' (None) - similar to 'g', except that it prints at least one digit after the decimal point.
2 of 2
1
A cheat sheet for f-string would be too short and kind of useless since f-string are super simple. If you want to put a number just do it. Ex. name: str = "Albus Dumbledore" age: int = 116 print(f"Name: {name}, Age: {age}") As you can see, I simply put age (which is an int) inside 2 brackets in the string (don't forget the f) and let Python do it's magic. (If you want you can use the example above as your cheat sheet)
๐ŸŒ
Bentley
cissandbox.bentley.edu โ€บ sandbox โ€บ wp-content โ€บ uploads โ€บ 2022-02-10-Documentation-on-f-strings-Updated.pdf pdf
Updated 2022 A Guide to Formatting with f-strings in Python
The procedure is as follows: โ€ข Placing between the quotation marks after the 'f' the text that you want displayed ยท โ€ข Enclosing the variables to be displayed within the text in curly braces ยท โ€ข Within those curly braces, placing a colon (:) after the variable ยท โ€ข Formatting the variable ...
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ formatted-strings
Python Formatted Strings / f-string formatting Guide
Introduced in Python 3.6, f-strings use curly braces ({ and }) to embed Python expressions inside string literals. The most modern and recommended way to format strings in Python is by using f-strings (formatted string literals).
Find elsewhere
๐ŸŒ
DEV Community
dev.to โ€บ tusharsadhwani โ€บ what-the-f-strings-391c
What the f-strings? - DEV Community
July 11, 2021 - Enter number of digits of pi: 8 Enter string length: 30 Enter alignment (<, > or ^): ^ Enter padding character: _ __________3.1415927___________ You can define custom format handling in your own objects by overriding the __format__ method on the formatter object. This allows you to define (mostly) arbitrary formatting semantics. Here's an example, with more sensible names for datetime formatting: from datetime import datetime class BetterDatetime(datetime): substitutions = { '๏ฟฝy': '%A', '๏ฟฝte': '%d', '%monthname': '%B', '%month': '%m', '%year': '%Y' } def __format__(self, format_spec): for token, replacement in self.substitutions.items(): format_spec = format_spec.replace(token, replacement) return super().__format__(format_spec) print(f'Today is {BetterDatetime.now():๏ฟฝy, ๏ฟฝte %monthname %year}') # Output: Today is Monday, 8 July 2021
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ what's better to use? (%), (f"string") or (.format())?
r/learnpython on Reddit: What's better to use? (%), (f"string") or (.format())?
November 25, 2024 -

I was trying to make a, silly program in which you can do some random things. I used arguments (%)in the past, but it's a bit hard to write like the identification of the variable, like there is so much types (%s, %f, %2f, %d, %g, %e...) and I want to take the easiest to write or the easiest to debug.

here are some examples of using each one:

  using (%):
name = "Imaginary_Morning"
age = 13
print("This profile is called %s and it has %d years old." % (name, age))
  
using (f"string"):
name = "Imaginary_Morning"
age = 13
print(f"This profile is called {name} and it has {age} years old.")

  using (.format()):
name = "Imaginary_Morning"
age = 13
print("This profile is called {} and it has {} years old.".format(name, age))
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ formatted-string-literals-f-strings-python
f-strings in Python - GeeksforGeeks
May 16, 2026 - An f-string is created by adding f before the string and placing variables or expressions inside {}. ... Example 1: This example formats and prints the current date using an f-string.
๐ŸŒ
Real Python
realpython.com โ€บ python-f-strings
Python's F-String for String Interpolation and Formatting โ€“ Real Python
November 30, 2024 - Python's f-strings provide a readable way to interpolate and format strings. They're readable, concise, and less prone to error than traditional string interpolation and formatting tools, such as the .format() method and the modulo operator ...
Top answer
1 of 16
995

To answer your first question... .format just seems more sophisticated in many ways. An annoying thing about % is also how it can either take a variable or a tuple. You'd think the following would always work:

"Hello %s" % name

yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you'd need to do

"Hello %s" % (name,)   # supply the single argument as a single-item tuple

which is just ugly. .format doesn't have those issues. Also in the second example you gave, the .format example is much cleaner looking.

Only use it for backwards compatibility with Python 2.5.


To answer your second question, string formatting happens at the same time as any other operation - when the string formatting expression is evaluated. And Python, not being a lazy language, evaluates expressions before calling functions, so the expression log.debug("some debug info: %s" % some_info) will first evaluate the string to, e.g. "some debug info: roflcopters are active", then that string will be passed to log.debug().

2 of 16
320

Something that the modulo operator ( % ) can't do, afaik:

tu = (12,45,22222,103,6)
print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*tu)

result

12 22222 45 22222 103 22222 6 22222

Very useful.

Another point: format(), being a function, can be used as an argument in other functions:

li = [12,45,78,784,2,69,1254,4785,984]
print map('the number is {}'.format,li)   

print

from datetime import datetime,timedelta

once_upon_a_time = datetime(2010, 7, 1, 12, 0, 0)
delta = timedelta(days=13, hours=8,  minutes=20)

gen =(once_upon_a_time +x*delta for x in xrange(20))

print '\n'.join(map('{:%Y-%m-%d %H:%M:%S}'.format, gen))

Results in:

['the number is 12', 'the number is 45', 'the number is 78', 'the number is 784', 'the number is 2', 'the number is 69', 'the number is 1254', 'the number is 4785', 'the number is 984']

2010-07-01 12:00:00
2010-07-14 20:20:00
2010-07-28 04:40:00
2010-08-10 13:00:00
2010-08-23 21:20:00
2010-09-06 05:40:00
2010-09-19 14:00:00
2010-10-02 22:20:00
2010-10-16 06:40:00
2010-10-29 15:00:00
2010-11-11 23:20:00
2010-11-25 07:40:00
2010-12-08 16:00:00
2010-12-22 00:20:00
2011-01-04 08:40:00
2011-01-17 17:00:00
2011-01-31 01:20:00
2011-02-13 09:40:00
2011-02-26 18:00:00
2011-03-12 02:20:00
๐ŸŒ
Fstring
fstring.help
fstring.help: Python f-string guide
The number behind a . in the format specifies the precision of the output. For strings, that means that the output is truncated to the specified length. In our example, this would be 5 characters. ... Some other representations are available too, such as converting the number into an unicode character: ... Similar to strings, numbers can also be constrained to a specific width. ... Again similar to truncating strings, the precision for floating ...
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ string-formatting
Python f-string tips & cheat sheets - Python Morsels
April 12, 2022 - Python's string formatting syntax allows us to inject objects (often other strings) into our strings. >>> name = "Trey" >>> print(f"My name is {name}. What's your name?") My name is Trey.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-f-string
Python f-string: A Complete Guide | DataCamp
December 3, 2024 - Weโ€™ll see how to evaluate expressions, format numbers and dates, handle multiline strings, and apply best practices in your code. F-strings provide a modern and intuitive way to format strings in Python by using a simple prefix and expression syntax.
๐ŸŒ
Littlecolumns
littlecolumns.com โ€บ learn โ€บ python โ€บ f-strings
Formatting output with f strings - Python's Not (Just) For Unicorns
It works just like a fill-in-the-blank. The f before the string says โ€œhey, weโ€™re going to put some variables in here!โ€ and the {name} says โ€œput the name variable in here!โ€ and then everyone is happy and we didnโ€™t have to use a hundred commands.
๐ŸŒ
OpenStax
openstax.org โ€บ books โ€บ introduction-python-programming โ€บ pages โ€บ 3-2-formatted-strings
3.2 Formatted strings - Introduction to Python Programming | OpenStax
March 13, 2024 - A formatted string literal (or f-string) is a string literal that is prefixed with "f" or "F". A replacement field is an expression in curly braces ({}) inside an f-string. Ex: The string f"Good morning, {first} {last}!" has two replacement ...
๐ŸŒ
Built In
builtin.com โ€บ data-science โ€บ python-f-string
Guide to String Formatting in Python Using F-strings | Built In
They provide a better way to format strings and make debugging easier, too. ... Summary: Python f-strings, introduced in version 3.6, allow cleaner string formatting by embedding variables directly.
๐ŸŒ
DZone
dzone.com โ€บ coding โ€บ languages โ€บ python f-strings
Python F-Strings
August 22, 2023 - The format specifier defines how the number should be formatted, including its precision, width, and alignment. The following script prints a floating-point number with only two decimal places: ... F-strings can also be used to round numbers ...
๐ŸŒ
Medium
medium.com โ€บ @bvvkrishna โ€บ f-strings-python-3-8-string-formatting-d69b9c4e47a
f-strings โ€” Python 3.8 String formatting | by Krishna B | Medium
January 6, 2020 - Earlier versions of python have raw string formatting using โ€œ%โ€ operator, format method of string data type, etc for formatting strings. f-strings is basically a literal string prefixed with โ€˜fโ€™ with expressions enclosed in braces. These expressions on the execution of the code will be replaced by values.