简体   繁体   中英

How to convert a string (with non-digit place value separators) into an integer?

price = '20,355' 

This is a python string variable. How do I convert it into an integer variable?

For example:

price = 20355 

This is my prefered way to convert strings with place-value separators to integers:

>>> import locale
>>> price = '20,355'
>>> locale.setlocale(locale.LC_NUMERIC, '')  # Or any other appropriate locale.
'English_United Kingdom.1252'
>>> locale.atoi(price)
20355

This is better than just replacing commas with empty-strings, because in some locales commas are used as decimal separators, while periods play the part of delimiting the thousands, millions etc.

您需要删除逗号:

price = int(price.replace(",", ""))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM