小编par*_*ty3的帖子

如何在python 3中实现字节对象的sprintf样式格式化?

我想在python3上做sprintf但是使用原始字节对象,而不必为%s进行任何手动转换.因此,将一个bytes对象作为"模板",加上任意类型的任意数量的对象,并返回一个呈现的字节对象.这就是python 2的sprintf%运算符一直在运行的方式.

b'test %s %s %s' % (5, b'blah','strblah') # python3 ==> error
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: %b requires bytes, or an object that implements __bytes__, not 'int'

def to_bytes(arg):
    if hasattr(arg,'encode'): return arg.encode()
    if hasattr(arg,'decode'): return arg
    return repr(arg).encode()

def render_bytes_template(btemplate : bytes, *args):
    return btemplate % tuple(map(to_bytes,args))

render_bytes_template(b'this is how we have to write raw strings with unknown-typed arguments? %s %s %s',5,b'blah','strblah')

# output: b'this is how we have to …
Run Code Online (Sandbox Code Playgroud)

python templates incompatibility bytestring python-3.x

9
推荐指数
1
解决办法
812
查看次数