4. int()和float()从字符串中取值误区

*爱你&永不变心* 提交于 2020-02-03 18:41:28

<!DOCTYPE html>

Untitled3

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS_HTML"></script>
<!-- MathJax configuration -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
        processEscapes: true,
        processEnvironments: true
    },
    // Center justify equations in code and markdown cells. Elsewhere
    // we use CSS to left justify single line equations in code cells.
    displayAlign: 'center',
    "HTML-CSS": {
        styles: {'.MathJax_Display': {"margin": 0}},
        linebreaks: { automatic: true }
    }
});
</script>
<!-- End of mathjax configuration --></head>

int()和float的区别

In [20]:
int('3')
Out[20]:
3
In [21]:
int('3.4')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-21-5e199bebc801> in <module>
----> 1 int('3.4')

ValueError: invalid literal for int() with base 10: '3.4'
In [22]:
float('3')
Out[22]:
3.0
In [23]:
float('3.4')
Out[23]:
3.4
In [24]:
int('中文')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-24-6662126cc8e2> in <module>
----> 1 int('中文')

ValueError: invalid literal for int() with base 10: '中文'
In [25]:
float('中文')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-25-60f801202537> in <module>
----> 1 float('中文')

ValueError: could not convert string to float: '中文'

int()和float虽然都是将字符串转换成整数,但是字符串中的数必须与自己契合,比如int()只能转换整数类型的,而float包含了int,所以能转换成int,和float类型的,并不什么类型的都能转换

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!