在 python 中使用具有 C 风格字符串格式的 f 字符串

using f-string with C-style string formatting in python

我想编写一个函数来构建一个字节类型的字符串,该字符串需要使用具有不同值的 f-string。我能想到的唯一方法就是遵循代码。任何人有更好的 建议?在代码中,我有像 这样的字符串,我有 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'>

您可以通过生成字符串然后调用它们的 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'>

为了你的测试