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.

classification
Title: Underscore in str.format with x option
Type: behavior Stage: resolved
Components: Versions: Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: cheryl.sabella, eric.smith, serhiy.storchaka
Priority: normal Keywords:

Created on 2018-03-06 15:08 by cheryl.sabella, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (4)
msg313330 - (view) Author: Cheryl Sabella (cheryl.sabella) * (Python committer) Date: 2018-03-06 15:08
From the doc (https://docs.python.org/3/library/string.html#format-specification-mini-language):

> The '_' option signals the use of an underscore for a thousands separator for floating point presentation types and for integer presentation type 'd'. For integer presentation types 'b', 'o', 'x', and 'X', underscores will be inserted every 4 digits. For other presentation types, specifying this option is an error.

>>> '{0:_}'.format(123456789)
'123_456_789'
>>> '{0:x}'.format(123456789)
'75bcd15'
>>> '{0:x_}'.format(123456789)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid format specifier

What am I doing wrong?  I read the doc as saying that using `type` of `x` would result in the `_` separator to be inserted every 4 characters, so I was expecting the output to be '75b_cd15'.

Thanks!
msg313334 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2018-03-06 15:50
>>> format(123456789, '_x')
'75b_cd15'
msg313336 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2018-03-06 15:51
The format specifier (here, 'x') always goes last.

>>> '{0:_x}'.format(123456789)
'75b_cd15'

See https://docs.python.org/3/library/string.html#formatstrings for the details.

Serhiy is correct that it's often easier to use format() instead of ''.format() for testing things like this.
msg313339 - (view) Author: Cheryl Sabella (cheryl.sabella) * (Python committer) Date: 2018-03-06 16:06
Thanks guys.

I really thought I tried '{0:_x}'.format(123456789), but I guess I hadn't.  Good to know that using format(123456879, '_x) is better.
History
Date User Action Args
2022-04-11 14:58:58adminsetgithub: 77194
2018-03-06 16:06:39cheryl.sabellasetmessages: + msg313339
2018-03-06 15:51:49eric.smithsetnosy: + eric.smith
messages: + msg313336
2018-03-06 15:50:08serhiy.storchakasetstatus: open -> closed

nosy: + serhiy.storchaka
messages: + msg313334

resolution: not a bug
stage: resolved
2018-03-06 15:08:53cheryl.sabellacreate