0

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'> 
1
  • 1
    Why not just .encode() the string? e.g. lambda x: f"<blah> ... {x} ...".encode() and then you just have 'level': name(size['v1']) Commented Aug 10, 2018 at 18:00

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

thx, but i should mention by output is not necessary in that sequence. update my question
@jacobcan118 I'm afraid I don't understand. Do you mean that the various leveln in your code are actually unrelated 600 character strings?
i mean my output is not necessary to be level1 to level3, it maybe get_level_string('level2'), get_level_string('level3'), get_level_string('level1') in random sequence
@jacobcan118 I still don't see the issue. __getitem__ doesn't affect the underlying dictionary, so i shouldn't matter what order you're calling them in.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.