0

This is a hackerrank practice problem https://www.hackerrank.com/challenges/python-string-formatting/problem . It is not actually a difficult problem, but one of the solutions posted in the discussion is confusing. I am adding their function for doing the same below:

def print_formatted(number):
    p = len(f"{number:b}")
    for i in range(1,number+1): print(f"{i: >{p}} {i: >{p}o} {i: >{p}X} {i: >{p}b}")
  1. Even though b is not defined it is not throwing an error. If I just do 5:6 in python, it throws an error. But if I do print(f"{5:6}"), it prints adds 6 spaces before 5 and prints it. What exactly is happening here and what are the common use cases for this?
  2. What exactly is happening in the print statement? What does all the o, X nd b do? Why is there a {} inside one active {} and what does it do?
Jihjohn
  • 398
  • 4
  • 19
  • 7
    It's all documented in the [docs](https://docs.python.org/3/library/string.html#formatspec) – rdas Sep 17 '22 at 18:18
  • 1
    And there is nothing "uncommon" in f-strings/string formatting, Quite the opposite. – buran Sep 17 '22 at 18:59

1 Answers1

0

Format Specification Mini-Language

“Format specifications” are used within replacement fields contained within a format string to define how individual values are presented (see Format String Syntax and Formatted string literals). They can also be passed directly to the built-in format() function. Each formattable type may define how the format specification is to be interpreted.

The available integer presentation types are:

Type Meaning
'b' Binary format. 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. In case '#' is specified, the prefix '0x' will be upper-cased to '0X' as well.
'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'.

Source

Shahab Rahnama
  • 982
  • 1
  • 7
  • 14