python中字符串怎么转换成int
将字符串转换成,整型,从字面理解很容易让人误会。
比如,要把这个"abcabc"转换成整型,臣妾做不到啊。除成转成ascii。
我们所说字符串转成整型是这样的。
s="12"
s="12.12"
我们自己写一个函数,来实现这个转换。
思想:python提供转换成整型用int()这关键字,那么,如果我这样int('12')int(12.12)这样是可以转成整型的。但是如果int('abc')int('12.12')会报类型错误
那么我们就利用无法转换的情况,会报类型错误来写这个函数。
实现:如果可以转换成,int型直接反回转换后的值,如果无法转换,反回False
defto_int(str):
try:
int(str)
returnint(str)
exceptValueError:#报类型错误,说明不是整型的
try:
float(str)#用这个来验证,是不是浮点字符串
returnint(float(str))
exceptValueError:#如果报错,说明即不是浮点,也不是int字符串。是一个真正的字符串
returnFalse
调用
printto_int('str')
printto_int('str123')
printto_int('12.12')
printto_int('234')
printto_int('12#$%%')
结果
D:\Python27\python.exeD:/HttpRunnerManager-master/HttpRunnerManager-master/test.py
False
False12
234False
以上内容为大家介绍了python中字符串怎么转换成int,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python如何用import语句
Python程序可以调用一组基本的函数(即内建函数),比如print()、input()和len()等函数。Python本身也内置一组模块(即标准库)。每个模块都是一个P...详情>>
2023-11-13 21:55:54
python代码如何运行
交互提示模式下编写代码安装完Python在Windows或Linux中的终端中直接输入python即进入Python交互会话模式。Python交互模式有以下几个注意点:1....详情>>
2023-11-13 20:54:58
python不是内部命令
‘python3’不是内部或外部命令,也不是可运行的程序或批处理文件。我将python安装在D盘之后,输入python,显示如下问题D:\>python'python&...详情>>
2023-11-13 19:50:57
python函数的参数有几种
python中函数的参数可以分为位置参数,关键字参数和默认参数。下面我们一一来讲解。位置参数,有时也称必备参数,指的是必须按照正确的顺序将实...详情>>
2023-11-13 16:42:21