Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use digit separators for Python integer literals?

Is there any way to group digits in a Python code to increase code legibility? I've tried ' and _ which are digit separators of some other languages, but no avail.

A weird operator which concatenates its left hand side with its right hand side could also work out.

like image 622
Utkan Gezer Avatar asked Jul 01 '16 23:07

Utkan Gezer


People also ask

How do you separate long numbers in Python?

Use the map() and str. split() Functions to Split an Integer Into Digits in Python. The map() function implements a stated function for every item in an iterable. The item is then consigned as a parameter to the function.

What is underscore in number in Python?

this is used for interpreting a mixed-type input data file. '_' was used as a delimiter to combine two integer id's in some fields and all of a sudden (after python 3.6 upgrade), these fields are converted into one integer!

What is a numeric literal in Python?

What are numeric literals? Numeric literals are used to represent numbers in a python program.In python we have different types of numeric literals such as integers, floating point numbers and complex numbers. Integers in python are numbers with no fractional component.


2 Answers

Update a few years later: Python 3.6 now supports PEP515, and so you can use _ for float and integer literal readability improvement.

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 1_1000 11000 >>> 

For historical reference, you can look at the lexical analysis for strict definitions python2.7, python3.5 ...

For python3.6.0a2 and earlier, you should get an error message similar to:

Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21)  [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> 1_000   File "<stdin>", line 1     1_000         ^ SyntaxError: invalid syntax >>> amount = 10_000_000.0   File "<stdin>", line 1     amount = 10_000_000.0                       ^ SyntaxError: invalid syntax 
like image 109
mgilson Avatar answered Sep 24 '22 19:09

mgilson


Currently there is no thousands separator in Python, but you can use locale module to convert string with such separators to an int:

import locale locale.setlocale(locale.LC_ALL, '') locale.atoi("1,000,000") 
like image 42
scope Avatar answered Sep 23 '22 19:09

scope