Python:' if num> 93'给我带来了像94,95,996,93456这样的数字

时间:2016-03-05 00:12:31

标签: python

今天是我的第一个Python日。

以下是代码:

for num, line in enumerate(fo, 1):
        if str(num) > '93971':
                fp.write(str(num) + "\t" + str(line))
fo.close()

奇怪的是,它给我带来了所有以94或97或9582等开头的数字

我怎样才能得到一个?

理想情况下,我正在尝试的是:

for num, line in enumerate(fo, 1):
            if str(num) > '93971':
                    fp.write(str(num) + "\t" + str(line))
            if str(num) < '110000':
                    break
    fo.close()

非常感谢!

编辑:

fo看起来如何:

text one
text 3
text none

这应该像我一样:

1 text one
2 text 3
3 text none
...

确实如此,但我需要得到我需要的东西,只能从第93971行到110000行。

例如:

93971 text test
93972 text test3
...
110000 text test2

2 个答案:

答案 0 :(得分:1)

进行字符串比较。您可能想要比较数字。假设第一行上的num是一个int - 它是从enumerate返回的索引 - 你应该这样做:

if num >= 93971 and num <= 110000:
    fp.write(str(num) + "\t" + line)  # assuming line is already a str,
                                      # no need to convert

fp.write行中,将其转换为strand比较进行两次比较,这两次比较都需要为真(因此在您想要的数字范围内)。根据您是否需要开头/结尾编号调整<= vs <

比较可以减少到if 93971 <= num <= 110000:

编辑:根据&#34;真实&#34;更正被问到的问题。

答案 1 :(得分:0)

只需比较整数而不是将事物转换为字符串。这是一个使用更小数字的工作示例

# write a test file
with open('test.txt', 'w') as fp:
    for i in range(1,1000):
        fp.write('line {}\n'.format(i))

# now read lines 99 through 108 (random example)
with open('test.txt') as fo, open('test2.txt', 'w') as fp:
    for num, line in enumerate(fo, 1):
        if num > 108:
            break
        elif num > 99:
            fp.write(str(num) + '\t' + line)

# now print what we wrote
print(open('test2.txt').read())

When run you get

 $ python3 k.py
100 line 100
101 line 101
102 line 102
103 line 103
104 line 104
105 line 105
106 line 106
107 line 107
108 line 108