Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (106k points)

Apparently, the following is valid syntax

my_string = b'The string'

I would like to know:

  1. What does this ‘b’ character in front of the string mean?

  2. What are the effects of using it?

  3. What are appropriate situations to use it?

I found a related question right here on SO, but that question is about PHP though, and it states the ‘b’ is used to indicate the string is binary, as opposed to Unicode, which was needed for the code to be compatible from a version of PHP < 6, when migrating to PHP 6. I don't think this applies to Python.

I did find this documentation on the Python site about using a u character in the same syntax to specify a string as Unicode. Unfortunately, it doesn't mention the ‘b’ character anywhere in that document.

Also, just out of curiosity, are there more symbols than the ‘b’ and ‘u’ that do other things?

2 Answers

0 votes
by (47.6k points)

  • The ‘b’ character is called bytes literals and is always prefixed with 'b' or 'B'. They produce an instance of the bytes type instead of the ‘str’ type. 

  • Strings are an abstraction, while bytes are the actual data. 

  • If you took a single character and you had multi-character string object then it would be a string, and it might be more than 1 byte in size depending on the encoding.

  • If you will take 1 byte with a byte string then you will get a single 8-bit value from 0-255 and it might not represent a complete character due to encoding those characters size becomes greater than 1 byte.

  • It is advised to use strings unless you had some specific low-level reason to use bytes.

0 votes
by (107k points)

Please be informed that the 'b' letter denotes a single byte string.

Basically, the bytes are recognized as the actual data. Strings are taken as an abstraction.

Let's suppose, if you take a multi-character string object and you only refer to a single character, it would be a string, and that character or string might be more than one-byte size.

For more information, refer to the Python certification course.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Sep 10, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...