字符串转化为数字

#给定一个字符串表示整数,将它转化为整数并输出
#例如字符串“345”输出整数345
#例如“-123”输出-123
#思路应该这样。既然是整数,要考虑正负,要考虑输入有非法字符,要考虑是否有溢出


input_char = raw_input("input your string")

translateNumber = 0
isAnumber = True
symbol = 'null'
for s in range(len(input_char)):
    if s == 0:
        if input_char[s] == '+':
            symbol = '+'
            continue
        elif input_char[s] == '-':
            symbol = '-'
            continue

    if not input_char[s].isdigit() and s != 0:
        isAnumber = False
        print "the string is not all number"
        break
    else:
        translateNumber *= 10
        translateNumber = translateNumber + int(input_char[s])

if isAnumber == True:
    print symbol,translateNumber

else:
    pass

 

posted on 2014-01-29 18:00  lgy111  阅读(299)  评论(0编辑  收藏  举报

导航