python--字符串转数字
今天遇到需要把字符串转为数字的情况,但是没有先判断字符串中是否有数字之外的,然后直接调用int()
然后运行就提示错误了
def slot_port_num(line): strlist = line.split('\n') total_port_num = 0 for singleline in strlist: slot_port_num = int(singleline) total_port_num = total_port_num + slot_port_num print("total port number:", total_port_num) return total_port_num
在调用int(singleline)之前,要先调用isdigit()判断singleline是否为全数字,修订之后如下
def slot_port_num(line): strlist = line.split('\n') total_port_num = 0 for singleline in strlist: if (singleline.isdigit()): slot_port_num = int(singleline) total_port_num = total_port_num + slot_port_num print("total port number:", total_port_num) return total_port_num
posted on 2014-08-23 01:13 chenliting 阅读(1988) 评论(0) 编辑 收藏 举报