Categories
Python Answers

How to convert a string to a number if it has commas in it as thousands separators with Python?

Spread the love

Sometimes, we want to convert a string to a number if it has commas in it as thousands separators with Python.

In this article, we’ll look at how to convert a string to a number if it has commas in it as thousands separators with Python.

How to convert a string to a number if it has commas in it as thousands separators with Python?

To convert a string to a number if it has commas in it as thousands separators with Python, we can use the locale module.

For instance, we write

import locale

locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) 
locale.atoi('1,000,000')

to call setlocale to set the locale.

Then we call locale.atoi to convert the string to an integer.

We can also use atof to convert the number string to float by writing

locale.atof('1,000,000.53')

Conclusion

To convert a string to a number if it has commas in it as thousands separators with Python, we can use the locale module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *