Home  >  Article  >  Backend Development  >  Problems encountered when Python's str is forcibly converted to int

Problems encountered when Python's str is forcibly converted to int

不言
不言Original
2018-04-09 15:10:422565browse

The following is an article to share with you to solve the problems encountered when Python's str is forced to int. It has certain reference value and I hope it will be helpful to everyone.

It’s okay if there are spaces before and after the numeric string:

>>> print(int(" 3 "))
3

But the following situation with decimal points It is not advisable:

>>> print(int("3.0"))
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: &#39;3.0&#39;

There is no problem in forcing this kind of string to float

>>> print(float("3.0"))
3.0

Related recommendations:

How to achieve mutual conversion from str to list in python

The above is the detailed content of Problems encountered when Python's str is forcibly converted to int. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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