Python 2.7 - 将单个字符串转换为整数

时间:2016-02-23 00:39:07

标签: python python-2.7 char int type-conversion

我正在尝试制作一个程序,它从两个文本文件中逐行读取并存储您之前在Name_Input中指定的行(在变量行和第2行中),然后删除任何不是字符串中的数字。

for line in Roster_Inputed:  

        if Name_Input in line: 
            line = re.sub('[^0-20]', '', line)

            if line == "1":
                print(Name_Input + " " + "should have " + line + " " + "ally.")  
                print " "  
            else:
                print(Name_Input + " " + "should have " + line + " " + "allies.")
                print " " 

    for line2 in Roster_Should_Have:
        if Name_Input in line2:
            line2 = re.sub('[^0-20]', '', line2)

            if line2 == "1":
                print(Name_Input + " " + "actually has " + line2 + " " + "ally.") 
                print " "   
            else:
                print(Name_Input + " " + "actually has " + line2 + " " + "allies.")
                print " " 

代码从两个包含空格后面的名称和数字的文件中读取,然后继续比较它们以确定它输出给用户的内容:

     if line == line2:
        print "All good"
    elif line != line2:
        print "Check " + Name_Input + "'s " + "spies"
        print " " 

我需要做的是检查“line”的值是否大于“line2”但是我不能这样做,因为它们是包含数字的字符串。有没有办法暂时将它们转换为整数?

3 个答案:

答案 0 :(得分:1)

您可以使用chr()ord()函数:

>>> chr(97)
'a'
>>> ord('a')
97

希望它有所帮助。

答案 1 :(得分:0)

如何调用int

>>> int('345')
345

答案 2 :(得分:0)

由于我现在已经确认字符将始终为整数并且整数是您想要比较的,我现在可以说使用int()

>>> int('4')
4

在你的情况下,if int(line) > int(line2):应该做你想要的。由于文件通常在每行末尾都有换行符,因此您应该考虑使用int(line.strip())int(line2.strip())