Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the b in front of string literals do?

Tags:

syntax

string

php

$binary = b'Binary string';

What consequences does it have to create a string as binary?

I couldn't find any hint about that in the documentation. Just found this little curiosity while looking through the language_scanner.

like image 527
NikiC Avatar asked Jan 20 '11 16:01

NikiC


People also ask

What is b in front of a string?

The b denotes a byte string. Bytes are the actual data.

What does the b character do in front of a string literal in Python?

A prefix of 'b' or 'B' is ignored in Python 2. In Python 3, Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.

What does b string mean?

The bytes data type literals in the Python b string represent values between 0 and 255, whereas the traditional string contains a sequence of Unicode characters such as UTF-16 or UTF-32. In Python, strings are used to represent text-based data and are contained in single or double-quotes.

What does b represent in Python?

The b" notation is used to specify a bytes string in Python. Compared to the regular strings, which have ASCII characters, the bytes string is an array of byte variables where each hexadecimal element has a value between 0 and 255.


2 Answers

This is a forward compatibility token for the never-to-be-released PHP version 6, which should have had native unicode support.

In PHP6, strings are unicode by default, and functions operate at the unicode character level on them. This "b" means "binary string", that is, a non unicode string, on which functions operate at the byte level.

This has no effect in PHP != 6, where all strings are binary.

like image 147
Arnaud Le Blanc Avatar answered Oct 24 '22 09:10

Arnaud Le Blanc


Binary casting is available since 5.2.1 but will not take effect until 6.0 when unicode strings also take effect.

Which explains why this does nothing special right now for me on a server using 5.2.6:

<?php
$t = b"hey";
var_dump($t);
//string(3) "hey"

$s = (binary)"hey";
var_dump($s);
//string(3) "hey"
?>
like image 35
brian_d Avatar answered Oct 24 '22 08:10

brian_d