Question:
Python throws a ValueError when attempting to convert a string with commas as thousands separators to an integer using the int() function. Is there a more efficient method to perform this conversion?
Answer:
The locale module in Python provides a solution. By setting the locale to 'en_US.UTF-8', you enable the correct interpretation of commas as thousands separators.
import locale locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )
With the locale set, you can use the locale.atoi() and locale.atof() functions to convert string representations to integers and floats, respectively:
locale.atoi('1,000,000') # Results in 1,000,000 locale.atof('1,000,000.53') # Results in 1,000,000.53
The above is the detailed content of How Can I Efficiently Convert a String with Thousands Separators to a Number in Python?. For more information, please follow other related articles on the PHP Chinese website!