创建基于字符串的数组在字符串之前引入随机'b'

时间:2017-08-08 16:27:50

标签: python arrays string list numpy

我正在尝试创建一个基本上是单词列表的表。我更喜欢表格式,因为它最终将进入excel。然而,在我的代码中,我不断在字符串之前引入字母'b'。任何帮助,将不胜感激。

我甚至尝试在各个阶段进行打印,以了解它们的介绍地点和原因。 代码:

from xlwt import Workbook
import numpy as np

wb = Workbook()
Number_Of_Days = int(input('How many days do you want?'))
All_Sheets = np.chararray((Number_Of_Days,1))
All_Sheets = np.chararray(All_Sheets.shape, itemsize = 10)
All_Sheets[:] = ''

print(All_Sheets)

count = 0
while count < Number_Of_Days:
    Sheet_Name = input(print('Enter the name of day', count+1))
    All_Sheets [count,0] = Sheet_Name
    count = count + 1

print(All_Sheets)

Code and output

1 个答案:

答案 0 :(得分:2)

请注意chararray文档:

  

chararray类的存在是为了向后兼容      Numarray,不建议用于新开发。从numpy开始      1.4,如果需要字符串数组,建议使用数组      dtype object_string_unicode_,并使用免费功能      在numpy.char模块中进行快速矢量化字符串操作。

In [191]: np.chararray((2,1))
Out[191]: 
chararray([[''],
           [b'\x01']],
          dtype='|S1')

&#39; | S1&#39; dtype表示一个字符的字节串。这是Py2中的默认类型,但在Py3中,它被标记为b字符。

初始化字符数组的更好方法是:

In [192]: np.zeros((2,1), dtype='U10')
Out[192]: 
array([[''],
       ['']],
      dtype='<U10')

In [194]: np.zeros((2,1), dtype='S10')
Out[194]: 
array([[b''],
       [b'']],
      dtype='|S10')
使用字符串列表

甚至更好:

In [195]: np.array(['one','two','three'])
Out[195]: 
array(['one', 'two', 'three'],
      dtype='<U5')