Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 541
pbaranski Avatar asked Dec 21 '18 09:12

pbaranski


People also ask

Can you combine R and F strings Python?

Formatted string literals can be combined with a raw string by prefixing the string with fr . Copied! Strings that are prefixed with r are called raw strings and treat backslashes as literal characters.

Is F string faster than concatenate?

Summary: Using the string concatenation operator is slightly faster than using format string literals. Unless you are performing many hundreds of thousands of string concatenations and need them done very quickly, the implementation chosen is unlikely to make a difference.


Video Answer


1 Answers

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')
like image 172
Ralf Avatar answered Oct 16 '22 13:10

Ralf