I am guessing you meant to include the curly braces in the second example (f"{3:pad_amount}")
The solution is to use another set of them. It’s not obvious that it would work, but it does! f"{3:{pad_amount}}" Answer from jamestwebber on discuss.python.org
Python.org
discuss.python.org › python help
Allow f-string to dynamically pad spaces - Python Help - Discussions on Python.org
June 27, 2023 - Example: # This works >>> print(f"{3:4}") '3 ' # However this does not work. >>> pad_amount: int = ... >>> print(f"3:pad_amount") ValueError: Unknown format code 'a' for object of type 'int' # I know this is the intended behavior, however the only other way to do this (or if you have better ways to do this please let me know) is using eval()
Top answer 1 of 14
1045
You can do this with str.ljust(width[, fillchar]):
Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than
len(s).
>>> 'hi'.ljust(10)
'hi '
2 of 14
648
For a flexible method that works even when formatting complicated string, you probably should use the string-formatting mini-language,
using either f-strings
>>> f'{"Hi": <16} StackOverflow!' # Python >= 3.6
'Hi StackOverflow!'
or the str.format() method
>>> '{0: <16} StackOverflow!'.format('Hi') # Python >=2.6
'Hi StackOverflow!'
Request: removing extra spaces in f-string
I came across the below code snippet today. black==23.12.0 does not remove the extra space after the f-string's colon: some_float = 5.0 some_string = f"{some_float: 0.3f}" I am using Python 3.11.7. More on github.com
Does anyone have a concise cheat sheet for f string formatting with numbers
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. More on reddit.com
How to use f string format without changing content of string?
How to use f string format without changing content of string · It will lose a space character in second line. How can I prevent this behavior? I want to make a function to print the text above but the value in f string depend on the length of value current_money. More on discuss.python.org
format - Add spaces at the beginning of the print output in python - Stack Overflow
I'm wondering how Am I suppose to add 4 spaces at the beginnings of the print outputs with f-string or format in python? This is what I use to print now: print('{: More on stackoverflow.com
ZetCode
zetcode.com › python › fstring
Python f-string - formatting strings in Python with f-string
May 11, 2025 - $ python main.py Fixed format: 123.457 Adaptive format: 12345.7 · F-strings support custom fill characters for padding when aligning text. Instead of just spaces or zeros, you can use any character to fill the extra space, which is useful for creating visual separators or decorative output.
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)
Python.org
discuss.python.org › python help
How to use f string format without changing content of string? - Python Help - Discussions on Python.org
June 15, 2022 - How to use f string format without changing content of string · It will lose a space character in second line. How can I prevent this behavior? I want to make a function to print the text above but the value in f string depend on the length of value current_money.
CoenRaets
jsonviewer.ai › python-f-string-padding
Python f String Padding[Complete Guide with Examples] - JSON Viewer
July 5, 2023 - For example, if you want to print ... Normally, empty spaces are added before or after values to align them, whereas leading zeros are added to numerical values by using spaces instead of zeros....
Top answer 1 of 2
1
There's a couple ways you could do it:
- If
Constantis really an unchanging constant, why not just
before your other string?print(f" {Constant}", ...) - With your current implementation, you are left-aligning to a width of 10 characters. If you swap that to right-align, like
'{:>12}'.format('Constant')("Constant" is 8 characters, 12 - 8 = 4 spaces) It will put 4 characters in front of the string.
Here's a Python f-string syntax cheat sheet I've used before:
https://myshell.co.uk/blog/2018/11/python-f-string-formatting-cheatsheet/
And the official docs: PEP 3101
2 of 2
0
You can use ' ' + string (as suggested), but a more robust approach could be:
string="Test String leading space to be added"
spaces_to_add = 4
string_length=len(string) + spaces_to_add # will be adding 4 extra spaces
string_revised=string.rjust(string_length)
result:
' Test String leading space to be added'
Python
bugs.python.org › issue44355
Issue 44355: Allow spaces in format strings - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/88521
Kanaries
docs.kanaries.net › topics › Python › python-f-string
Python F-Strings: The Complete Guide to String Formatting – Kanaries
February 13, 2026 - name = "Alice" role = "Data Scientist" years = 5 bio = ( f"Name: {name}\n" f"Role: {role}\n" f"Experience: {years} years\n" f"Seniority: {'Senior' if years >= 5 else 'Mid-level'}" ) print(bio) # Output: # Name: Alice # Role: Data Scientist # Experience: 5 years # Seniority: Senior · This second approach avoids the leading newline and indentation issues that sometimes come with triple-quoted strings. Python 3.8 added the = specifier to f-strings, and it is one of the most useful debugging features in the language.
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
their squares and cubes, using spaces to align the columns. Notice the use of the field width to ... This also demonstrates how the use of a value for width will enable the columns to line up. The following program demonstrates the use of strings, decimals, and floats, as well as tabs for · a type of report that is often produced in a typical Python program.
GeeksforGeeks
geeksforgeeks.org › fill-a-python-string-with-spaces
Fill a Python String with Spaces - GeeksforGeeks
February 13, 2023 - Separating the first word from a string involves ide ... In Python, string.whitespace is a string containing all the characters that are considered whitespace. Whitespace characters include spaces, tabs, newlines and other characters that create space in text.