2017-08-08 102 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')