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

Python 2.7-将单个字符串转换为整数,python,python-2.7,char,int,type-conversion,Python,Python 2.7,Char,Int,Type Conversion,我试图制作一个程序,逐行读取两个文本文件,并存储您在前面的Name\u Input中指定的行(在变量行和第2行中),然后从字符串中删除任何不是数字的内容 for line in Roster_Inputed: if Name_Input in line: line = re.sub('[^0-20]', '', line) if line == "1": print(Name_Input +

我试图制作一个程序,逐行读取两个文本文件,并存储您在前面的
Name\u 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”,但是我不能这样做,因为它们是包含数字的字符串。有没有办法将它们临时转换为整数?

您可以使用和函数:

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

希望有帮助。

打电话给
int
怎么样

>>> int('345')
345

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


在您的情况下,
if int(line)>int(line2):
应该做您想做的事情。由于文件通常在每行的末尾都有新的行字符,所以您应该考虑使用<代码> int(行.d)(<代码> >和<代码> int(LINE.String())< /P> > /P>这取决于您所说的“更大”。如果字符串中的值大于另一个(实际数字),字符总是数字?变量“line”和“line 2”的内容总是数字,是的。是的!非常感谢你。
>>> int('4')
4