Home > Backend Development > Python Tutorial > How Can I Efficiently Convert a String with Thousands Separators to a Number in Python?

How Can I Efficiently Convert a String with Thousands Separators to a Number in Python?

DDD
Release: 2024-12-01 10:17:14
Original
837 people have browsed it

How Can I Efficiently Convert a String with Thousands Separators to a Number in Python?

Converting String with Thousands Separators into Number in Python

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' )
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template