我的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()
答案 0 :(得分:1)
str.format是在Python 2.6中引入的来自the doc
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.
答案 1 :(得分:0)
format
字符串的方法在版本低于2.6的python中不可用。使用%
运算符尝试以下操作:
print " ".join('%02x' % ord(c) for c in match)