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?

2
  • 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'. Commented Oct 23, 2020 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)] Commented Oct 23, 2020 at 21:28

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How can it be closed?
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.