我想编写一个函数来构建一个字节类型的字符串,该字符串需要使用具有不同值的f字符串。我能想到的唯一方法就是以下代码。任何人都有更好的 建议?在代码中,我有类似 I level 的字符串,但在我的实际代码中,字符串约为600个字符
def get_level_string(x):
size = dict(v1=1, v2= 200, v3= 30000)
s = size.get('v1')
name = lambda x: f"I have level value as {x} in the house"
return {
'level1': b'%a' % (name(size['v1'])),
'level2': b'%a' % (name(size['v2'])),
'level3': b'%a' % (name(size['v3'])),
}[x]
a = get_level_string('level1')
b = get_level_string('level2')
c = get_level_string('level3')
print(a, type(a))
print(b, type(b))
print(c, type(c))
=> #b"'I have level value as 1 in the house'" <class 'bytes'>
=> #b"'I have level value as 200 in the house'" <class 'bytes'>
=> #b"'I have level value as 30000 in the house'" <class 'bytes'>
答案 0 :(得分:1)
通过生成字符串,然后调用它们的encode
方法以使其成为bytes
对象,可以使此过程更加简单。请注意,您的函数实际上只是建立一个字典,然后在其中查找内容。仅一次构建字典,然后以不同的名称提供绑定的__getitem__
方法要简单得多。
template = "I have level value as {} in the house"
size_list = (1, 200, 30000)
sizes = {f"level{i}": template.format(x).encode() for i, x in enumerate(size_list, start=1)}
get_level_string = sizes.__getitem__
# tests
a = get_level_string('level1')
b = get_level_string('level2')
c = get_level_string('level3')
print(a, type(a))
print(b, type(b))
print(c, type(c))
打印
b'I have level value as 1 in the house' <class 'bytes'>
b'I have level value as 200 in the house' <class 'bytes'>
b'I have level value as 30000 in the house' <class 'bytes'>
用于测试