如果字符串中有逗号作为千位分隔符,如何将字符串转换为数字? [英] How to convert a string to a number if it has commas in it as thousands separators?

查看:86
本文介绍了如果字符串中有逗号作为千位分隔符,如何将字符串转换为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,它代表一个使用逗号分隔千位的数字.如何在 python 中将其转换为数字?

<预><代码>>>>int("1,000,000")

生成ValueError.

我可以在尝试转换之前用空字符串替换逗号,但不知何故感觉不对.有没有更好的办法?

解决方案

import localelocale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )locale.atoi('1,000,000')# 1000000locale.atof('1,000,000.53')# 1000000.53

I have a string that represents a number which uses commas to separate thousands. How can I convert this to a number in python?

>>> int("1,000,000")

Generates a ValueError.

I could replace the commas with empty strings before I try to convert it, but that feels wrong somehow. Is there a better way?

解决方案

import locale
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) 
locale.atoi('1,000,000')
# 1000000
locale.atof('1,000,000.53')
# 1000000.53

这篇关于如果字符串中有逗号作为千位分隔符,如何将字符串转换为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆