Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

python - How to convert a numeric string with place-value commas into an integer?

In Python, what is a clean and elegant way to convert strings like "1,374" or "21,000,000" to int values like 1374 or 21000000?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It really depends where you get your number from.

If the number you are trying to convert comes from user input, use locale.atoi(). That way, the number will be parsed in a way that is consistent with the user's settings and thus expectations.

If on the other hand you read it, let's say, from a file, that always uses the same format, use int("1,234".replace(",", "")) or int("1.234".replace(".", "")) depending on your situation. This is not only easier to read and debug, but it's not affected by the user's locale setting, so your parser will work on any system.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...