Search code examples
pythonf-string

How to merge f string with b string in one line usage in Python


I can create b-sting this way:
name_binary = b'Adam'
but if I have variable like name='Adam' and I want to make at once usage of f-string and b-string:
name_binary = fb'{name}'
I get:

   File "<input>", line 1
    c = fb'{a}'
              ^
SyntaxError: invalid syntax

I know that I can do:
name_binary = name.encode('utf-8')

But technicality is that possible by using b and f together as on my example?


Solution

  • No, what you want has been proposed but rejected till now.

    Read more about it in PEP-489:

    No binary f-strings

    For the same reason that we don't support bytes.format(), you may not combine 'f' with 'b' string literals.


    The options you have (like you already mentioned) would be:

    name_binary = f'{name}'.encode('utf-8')
    

    or

    name_binary = name.encode('utf-8')