如何知道大于运算符是否在代码中工作

时间:2019-01-29 13:33:12

标签: python

如果class UserCell: UITableViewCell { override func layoutSubviews() { super.layoutSubviews() textLabel?.frame = CGRect(x: 0, y: 0, width: textLabel!.frame.width, height: textLabel!.frame.height) textLabel?.backgroundColor = UIColor.red //only for demonstration textLabel?.sizeToFit() //detailtextlabel code } } 中的数字大于seqnum,我试图删除第一位数字。

999

预期:

import re

filename = raw_input('Enter a filename:')
pattern = re.compile(r'SEQNO')

with open(filename) as f:
  for line in f:
    if pattern.search(line):
      seqnum = line.split(' ')[1]
      print seqnum
  if seqnum > 999:
    print seqnum[1:]
  else:
    print "Seq Number is not greater than 999"

输出:

Enter a filename:20181023.112225.11308.1.2
654

实际:

Seq Number is not greater than 999

输出:
    54

1 个答案:

答案 0 :(得分:1)

您需要将string转换为int

替换此:

seqnum = line.split(' ')[1]

具有:

seqnum = int(line.split(' ')[1])

或者这个:

if seqnum > 999:

与此:

if int(seqnum) > 999:

因此:

with open(filename) as f:
  for line in f:
    if pattern.search(line):
        seqnum = int(line.split(' ')[1])
        print(seqnum)
    if seqnum > 999:
        print(seqnum[1:])
    else:
        print("Seq Number is not greater than 999")

编辑:

看起来很可能您正在使用Python 2.7,因为以下代码段可以在其中运行:

Python 2.7:

seqnum = "654"

if seqnum > 999:
     print(seqnum[1:])
else:
     print("Seq Number is not greater than 999")

输出:

54

相同的代码段,但是会在Python 3.x中引发错误:

Python 3.7:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    if seqnum > 999:
TypeError: '>' not supported between instances of 'str' and 'int'