Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'h' mean in a python format string?

This is a valid python format string:

>>> wierd_format = '[%27he]'
>>> print wierd_format % 2.5
[        2.500000e+00]

But this isn't:

>>> bad_format = '[%20qe]'
>>> print bad_format % 2.5
Traceback (most recent call last):
  File "prog.py", line 5, in <module>
    print bad_format % 2.5
ValueError: unsupported format character 'q' (0x71) at index 4

Clearly, h is a supported format character. However, the documentation doesn't mention an h specifier. What does it do?

like image 843
Eric Avatar asked Aug 11 '13 17:08

Eric


People also ask

What is .2f in Python?

A format of . 2f (note the f ) means to display the number with two digits after the decimal point. So the number 1 would display as 1.00 and the number 1.5555 would display as 1.56 . A program can also specify a field width character: x = 0.1.

Why %I is used in Python?

The reason why there are two is that, %i is just an alternative to %d ,if you want to look at it at a high level (from python point of view). Here's what python.org has to say about %i: Signed integer decimal. And %d: Signed integer decimal. %d stands for decimal and %i for integer.

What is string format () in Python?

Python String format() is a function used to replace, substitute, or convert the string with placeholders with valid values in the final string. It is a built-in function of the Python string class, which returns the formatted string as an output. The placeholders inside the string are defined in curly brackets.

What is %s and %D Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42)) Would output Joe is 42 years old.


1 Answers

From the docs:

A length modifier (h, l, or L) may be present, but is ignored as it is not necessary for Python – so e.g. %ld is identical to %d.

like image 182
Maciej Gol Avatar answered Oct 04 '22 21:10

Maciej Gol