2017-08-08 101 views
1

我试图创建一个基本上是单词列表的表。我更喜欢表格格式,因为它最终会进入excel。但是,通过我的代码,我不断在字符串之前获得字母'b'的介绍。任何帮助,将不胜感激。创建基于字符串的数组在字符串前引入随机'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

+0

这表明你正在寻找一个字节的文字,而不是字符串:https://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal – Jeremy

+0

@Jeremy谢谢你的快速回复。无论如何,我可以使我的输入字符串,并注意在这种情况下的字节文字? 而且当我把它放入时,excel会显示b'...'或者会被忽略? – newbieintown

+0

这将有助于转换:https://stackoverflow.com/questions/606191/convert-bytes-to-a-python-string至于Excel会发生什么,我真的不知道。 – Jeremy

回答

2

注意chararray文档:

chararray类存在与 Numarray向后兼容,不建议进行新的开发。从numpy的 1.4开始,如果需要的字符串数组,建议使用 dtypeobject_string_unicode_阵列,以及numpy.char模块快速矢量字符串操作中使用免费的功能 。

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

的 '| S1' D型是指一个字符字节串。这是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')