要在Python中将字符串(or any other type that can be converted)转换为整数,只需调用^{}内置函数。int()将raisea^{}如果失败,您应该特别注意:
在Python 2中。x:
>>>for value in '12345', 67890, 3.14, 42L, 0b010101, 0xFE, 'Not convertible':
... try:
... print '%s as an int is %d' % (str(value), int(value))
... except ValueError as ex:
... print '"%s" cannot be converted to an int: %s' % (value, ex)
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'
在Python 3中。x
语法略有变化:
>>>for value in '12345', 67890, 3.14, 42, 0b010101, 0xFE, 'Not convertible':
... try:
... print('%s as an int is %d' % (str(value), int(value)))
... except ValueError as ex:
... print('"%s" cannot be converted to an int: %s' % (value, ex))
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'
在使用try/except块时,必须明确要捕获的异常。
string = "abcd"
try:
i = int(string)
print i
except ValueError:
#Handle the exception
print 'Please enter an integer'
Try/Excepts功能强大,因为如果某个程序以多种不同的方式失败,您可以指定希望程序在每次失败时如何反应。
这里是:
s = "123"
try:
i = int(s)
except ValueError as verr:
pass # do job to handle: s does not contain anything convertible to int
except Exception as ex:
pass # do job to handle: Exception occurred while converting to int
最近做的一个案例要将时间数据进行聚类分析,所以需要将Timedelta转化为int或float数值形式。时间数据如下图所示:
方法(一):
通过pandas处理数据
结果如下图
方法(二):
通过numpy处理数据
结果如下图
总结:方法(一)pandas是直接提取days数值,如90 days 04:48:00提取数值90;方法(二)numpy是把整个时间进行换算,如90 days 04:48:00转化为90.200000。可以根据实际需求,选择不同的方法进行时间转换。
可以使用强制类型转换、自动类型转换两种方式。强制类型转换是通过类型转换运算来实现的。自动转换是在源类型和目标类型兼容以及目标类型广于源类型时发生一个类型到另一类的转换。
C语言常用数据类型,int:整数类型,float:单精度浮点类型,double:双精度浮点类型,char:字符类型,char*:字符指针类型。