Home > Backend Development > Python Tutorial > How Can I Convert Comma-Separated Strings to Numbers in Python?

How Can I Convert Comma-Separated Strings to Numbers in Python?

DDD
Release: 2024-12-24 13:21:51
Original
700 people have browsed it

How Can I Convert Comma-Separated Strings to Numbers in Python?

Converting Comma-Separated Strings to Numbers in Python

When encountering a string representing a number with commas inserted as thousand separators, converting it to a numeric value can present a challenge. Attempting to cast the string directly to an integer using int() will result in a ValueError.

Instead of manually removing the commas, a more elegant solution is to use the locale module in Python. By setting the locale to an English-based format, the locale module enables numbers to be parsed appropriately.

To demonstrate, import the locale module and set the locale to en_US.UTF-8:

import locale
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) 
Copy after login

Once the locale is set, the locale.atoi() and locale.atof() functions can be utilized to convert comma-separated strings to integers and floating-point numbers, respectively:

locale.atoi('1,000,000')
# 1000000

locale.atof('1,000,000.53')
# 1000000.53
Copy after login

By leveraging the locale module, you can effortlessly convert strings with comma-separated thousands separators to numeric values in Python, without interfering with the original string.

The above is the detailed content of How Can I Convert Comma-Separated Strings to Numbers 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