The reason for this error is that the format specifier d is specifically for formatting integers, not floats.You can use the general format specifier f instead.

f'{int(1223.555):5d}'
Answer from 911 on Stack Overflow
🌐
Bentley
cissandbox.bentley.edu › sandbox › wp-content › uploads › 2022-02-10-Documentation-on-f-strings-Updated.pdf pdf
A Guide to Formatting with f-strings in Python - CIS Sandbox
The variable, variable, is enclosed in curly braces { }. When variable = 10, the f-string · understands that variable is an integer and displays it as such.
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)
🌐
datagy
datagy.io › home › python posts › python f-strings: everything you need to know!
Python f-strings: Everything you need to know! • datagy
December 20, 2022 - F-strings can also be used to apply number formatting directly to the values. Python can take care of formatting values as percentages using f-strings.
🌐
Built In
builtin.com › data-science › python-f-string
Guide to String Formatting in Python Using F-strings | Built In
More on Python: 5 Types of Arguments in Python Function Definitions · There are very few occasions when you’d need to align a word or text to the right or left, but this is the foundation to fully understanding how to add zeros to the left or right of a number. F-string is very useful when formatting numbers.
🌐
OpenStax
openstax.org › books › introduction-python-programming › pages › 3-2-formatted-strings
3.2 Formatted strings - Introduction to Python Programming | OpenStax
March 13, 2024 - F-strings provide a convenient way to combine multiple values into one string. ... Programs often need to display numbers in a specific format. Ex: When displaying the time, minutes are formatted as two-digit integers.
🌐
Geeksta
geeksta.net › geeklog › python-number-formatting-f-strings
Python Number Formatting Made Easy with f-Strings | Geeksta
September 12, 2024 - Learn how to format numbers in Python with f-strings. Use format_spec to specify width, alignment, scientific notation, and more.
Find elsewhere
🌐
Real Python
realpython.com › python-f-strings
Python's F-String for String Interpolation and Formatting – Real Python
November 30, 2024 - Note that the number of objects in the tuple must match the number of format specifiers in the string: ... >>> name = "Jane" >>> age = 25 >>> "Hello, %s! You're %s years old." % (name, age) 'Hello, Jane! You're 25 years old.' In this example, you use a tuple of values as the right-hand operand to %. Note that you’ve used a string and an integer. Because you use the %s specifier, Python converts both objects to strings.
🌐
W3Schools
w3schools.com › python › python_string_formatting.asp
Python String Formatting
To format values in an f-string, add placeholders {}, a placeholder can contain variables, operations, functions, and modifiers to format the value. ... A placeholder can also include a modifier to format the value.
🌐
Fstring
fstring.help › cheat
Python f-string cheat sheet
See fstring.help for more examples and for a more detailed discussion of this syntax see this string formatting article. The below examples assume the following variables: ... These format specifications only work on all numbers (both int and float). 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.
🌐
Python Morsels
pythonmorsels.com › string-formatting
Python f-string tips & cheat sheets - Python Morsels
April 12, 2022 - These string formatting techniques work on all numbers (both int and float): There's also g, G, e, E, n, and F types for floating point numbers and c, o, and n types for integers which I haven't shown but which are documented in the format specification mini-language documentation.
🌐
OneUptime
oneuptime.com › home › blog › how to use f-strings for string formatting in python
How to Use f-strings for String Formatting in Python
January 25, 2026 - F-strings provide powerful number formatting options: # Integer formatting num = 42 print(f"Binary: {num:b}") # Binary: 101010 print(f"Octal: {num:o}") # Octal: 52 print(f"Hex: {num:x}") # Hex: 2a print(f"Hex upper: {num:X}") # Hex upper: 2A ...
Top answer
1 of 3
9

f"..." expressions format values to strings, integrate the result into a larger string and return that result. That's not quite the same as 'casting'*.

number is an expression here, one that happens to produce an integer object. The integer is then formatted to a string, by calling the __format__ method on that object, with the first argument, a string containing a format specifier, left empty:

>>> number = 10
>>> number.__format__('')
'10'

We'll get to the format specifier later.

The original integer object, 10, didn't change here, it remains an integer, and .__format__() just returned a new object, a string:

>>> f"{number} is not a string"
'10 is not a string'
>>> number
10
>>> type(number)
int

There are more options available to influence the output by adding a format specifier to the {...} placeholder, after a :. You can see what exact options you have by reading the Format Specification Mini Language documentation; this documents what the Python standard types might expect as format specifiers.

For example, you could specify that the number should be left-aligned in a string that's at least 5 characters wide, with the specifier <5:

>>> f"Align the number between brackets: [{number:<5}]"
'Align the number between brackets: [10   ]'

The {number:<5} part tells Python to take the output of number.__format__("<5") and use that as the string value to combine with the rest of the string, in between the [ and ] parts.

This still doesn't change what the number variable references, however.


*: In technical terms, casting means changing the type of a variable. This is not something you do in Python because Python variables don't have a type. Python variables are references to objects, and in Python it is those objects that have a type. You can change what a variable references, e.g. number = str(number) would replace the integer with a string object, but that's not casting either.

2 of 3
2

You can test it yourself quite easily

number = 10
print(f"{number} is not a string")

print(type(number))
# output is integer
🌐
Miguendes
miguendes.me › 73-examples-to-help-you-master-pythons-f-strings
Python F-String: 73 Examples to Help You Master It
July 2, 2022 - PEP 498 presented this new string interpolation to be a simple and easy to use alternative to str.format. The only thing required is to put a 'f' before a string. And if you're new to the language, that's what f in Python means, it's a new syntax to create formatted strings.
🌐
Cheatography
cheatography.com › brianallan › cheat-sheets › python-f-strings-number-formatting › pdf pdf
Python F-Strings Number Formatting Cheat Sheet
March 16, 2022 - (Guide​)" by Joanna Jablonski at Real Python: https:​//r​eal​pyt​hon.co​‐ ... https:​//d​ocs.py​tho​n.o​rg/​3/l​ibr​ary​/st​rin​g.h​tml​#fo​rma​t-s​tri​ng-​syntax · "​2.4.3. Formatted string litera​ls" from the page "2.
🌐
GeeksforGeeks
geeksforgeeks.org › formatted-string-literals-f-strings-python
f-strings in Python - GeeksforGeeks
June 19, 2024 - In Python, a string of required formatting can be achieved by different methods. Some of them are; 1) Using % 2) Using {} 3) Using Template Strings In this article the formatting using % is discussed. The formatting using % is similar to that of 'printf' in C programming language. %d - integer %f -
🌐
DataCamp
datacamp.com › tutorial › python-f-string
Python f-string: A Complete Guide | DataCamp
December 3, 2024 - F-strings are string literals prefixed with 'f' or 'F' that contain expressions inside curly braces {}. These expressions are evaluated at runtime and then formatted using the __format__ protocol. Unlike traditional string formatting methods, f-strings provide a more straightforward and readable way to embed Python expressions directly within string literals.
🌐
Finxter
blog.finxter.com › home › learn python blog › f-string python hex, oct, and bin: efficient number conversions
F-String Python Hex, Oct, and Bin: Efficient Number Conversions - Be on the Right Side of Change
March 27, 2023 - In this section, we’ll focus on the binary representation using f-strings. 😄 · To display a binary value of an integer using f-strings, you can use the formatting specifier b followed by the variable you want to convert inside the curly braces.