0

我的 Python 版本是 2.4.3,我想在代码下面运行,但我收到 str 格式错误。这是错误:

[xxx@bdm ~/python]$ ./run.sh
rfb.pcap
RFB\x20[0-9][0-9][0-9][.][0-9][0-9][0-9]\x0a
Traceback (most recent call last):
File "py_regex.py", line 14, in ?
print " ".join("{0:02x}".format(ord(c)) for c in match)
File "py_regex.py", line 14, in <generator expression>
print " ".join("{0:02x}".format(ord(c)) for c in match)
AttributeError: 'str' object has no attribute 'format'

这是我的代码:

#!/usr/bin/env python  
import re
import sys
file = sys.argv[1]
exp = sys.argv[2]
print file
print exp
myfile = open(file, "r")
try:
data = myfile.read()
p = re.compile(exp)
matches = p.findall(data)
for match in matches:
      print " ".join("{0:02x}".format(ord(c)) for c in match)

最后:myfile.close()

4

2 回答 2

1

str.format 在 Python 2.6 中引入

文档

format(value[, format_spec])¶
    Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.

    Note
    format(value, format_spec) merely calls value.__format__(format_spec).
    New in version 2.6.
于 2013-11-05T18:31:28.820 回答
0

format字符串方法在低于 2.6 的 python 中不可用。使用运算符尝试以下%操作:

print " ".join('%02x' % ord(c) for c in match)
于 2013-11-05T18:44:10.550 回答