What is the difference between a string and a byte string?

  • What does adding b' ' to a string exactly do?
  • Are the data types for strings and byte strings the same?
  • What will happen if I compare a string and a byte string using comparison operators such as >, < and ==?
1 Like

Let us first list the differences between and a string and a Byte string in Python 3.

  • Strings are a sequence of characters and Byte Strings are a sequence of bytes.
  • Strings exist as they can be read by humans and Byte Strings can be read by machines.
  • Strings need to be encoded first to be stored onto a disk and Byte Strings can be stored directly.
  • Strings can contain all sorts of characters and Byte Strings can only contain ASCII literal characters.

Now let us look at some examples consisting of byte strings.

Input:

b'This is a good day.'

Output:

b'This is a good day'

Input:

b'यह एक अच्छा दिन है'

Output:

b'यह एक अच्छा दिन है'
 ^
SyntaxError: bytes can only contain ASCII literal characters.

Here, we see a sentence in the Hindi language that can not be taken as a Bytes String and Python throws a SyntaxError.

Also, let us see the data type of both the strings.

Input:

byte_string = b'This is a good day.'
string = 'This is a good day.'
a = type(byte_string)
b = type(string)
print("The data type of Byte String is {} and a string is {}".format(a, b))

Output:

The data type of Byte String is <class 'bytes'> and a string is <class 'str'>

As Strings and Byte Strings belong to different data types, let me show you how the comparison operators such as >, < and == will work on both of them.

Input:

'day' < 'night'

Output:

True

Input:

'day' < b'night'

Output:

TypeError: '<' not supported between instances of 'str' and 'bytes'

Input:

'day' == b'day'

Output:

False

We can now say that that we can not compare bytes and str in the instances of > and < but comparing the two for equality == will give us a False output.

1 Like