1

I'm confused as to why the following code answer is:

import numpy as np
dt=[('name','S16'),('grad',int),('cpg',float)]
val=[("Ahmadmm",2008,12),('ali',2010,12.2),('mitra',505,15.15)]
arr=np.array(val,dtype=dt)
print(arr)

output:  [(b'Ahmadmm', 2008, 12.  ) (b'ali', 2010, 12.2 ) (b'mitra',  505, 15.15)]

Why there is a 'b' before each string?

MarianD
  • 13,096
  • 12
  • 42
  • 54
  • This question have to be reopened — the OP didn't ask ”**What** does the 'b' character do in front of a string literal?” but **why** there it is. He obviously wants the string output instead of the bytes one, and not an explanation of the 'b'. – MarianD Oct 23 '20 at 21:16
  • 2
    Instead of your `('name','S16')` use `('name', ' U16')`. **S** mean the string datatype, **U** is the Unicode one. — Then the output will be `[('Ahmadmm', 2008, 12. ) ('ali', 2010, 12.2 ) ('mitra', 505, 15.15)]` – MarianD Oct 23 '20 at 21:28

2 Answers2

1

I think this post answers your question: What does the 'b' character do in front of a string literal?. The 'b' character is basically indicating a byte literal.

Bram Dekker
  • 631
  • 1
  • 7
  • 19
1

As NPE stated in this question, to quote the Python 2.x documentation:

A prefix of 'b' or 'B' is ignored in Python 2; it indicates that the literal should become a bytes literal in Python 3 (e.g. when code is automatically converted with 2to3). A 'u' or 'b' prefix may be followed by an 'r' prefix.

The Python 3 documentation states:

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.

Saeed
  • 3,255
  • 4
  • 17
  • 36