jacobcan118
jacobcan118

Reputation: 9099

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

I would like to write a function to build a bytes type string that need to use f-string with different value. the only way I can think about is like following code. anyone have better suggestion? In code, I have string like I have level but in my actual code the string is about 600 charactors

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'>

Upvotes: 0

Views: 593

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 61063

You can make this a good deal simpler, by generating the strings and then calling their encode method to make them bytes objects. Note that your function really just builds a dictionary and then looks stuff up in it. It's much simpler to build the dictionary only once and then supply the bound __getitem__ method under a different name.

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))

prints

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'>

for your tests

Upvotes: 1

Related Questions