2017-03-14 23 views
0

我是一名python學習者。試圖從字符串列表中刪除標點符號並創建新列表但失敗。刪除字符串中的標點符號並將其附加到Python列表中

string_list = ['Jingle Bells.', "Donkey Kong's", "Jumping Jehosophat;"] 
strings_modified = [] 
for s in string_list: 
    strings_modified.append.str(s).translate(None, string.punctuation) 

我收到的錯誤是:

--------------------------------------------------------------------------- 
AttributeError       Traceback (most recent call last) 
<ipython-input-316-5c979f5c8af8> in <module>() 
     2 strings_modified = [] 
     3 for s in string_list: 
----> 4  strings_modified.append.str(s).translate(None, string.punctuation) 

AttributeError: 'builtin_function_or_method' object has no attribute 'str' 
+3

需要追加,無需轉換爲字符串後的括號:strings_modified.append(s.translate(無,string.punctuation)) – FLab

+1

不要使用'append.str(s)'使用'append(str(s))' –

+0

問題是我的類型是unicode。 'type(string_list [0])'是'unicode'。如果我不使用str,我得到這個錯誤:'TypeError:translate()只需要一個參數(給出2)'。所以我最終使用'str(s)'。但是這又產生了另一系列問題。當我嘗試在strings_modified中對sm進行操作時: strings_modified.append(sm.replace(「」,「+」))',python只是掛起。 。 。 – vagabond

回答

1

正如已經在評論原來的文章中提到有一個在串錯字

strings_modified.append.str(s) 

它必須是

strings_modified.append(str(s)) 

但是由於translate方法的簽名已經在Python 3中更改了,新的ve rsion可以看起來像:

trans_dict = {ord(i):None for i in string.punctuation} 

for s in string_list: 
    strings_modified.append(s.translate(trans_dict)) 

或者,使用列表理解(更Python)

strings_modified = [s.translate(trans_dict) for s in string_list] 
0

它看起來像你的代碼是非常複雜的。如果我們有一個功能fcn去除,我們可以使用Python的列表解析生成輸出。

類似於:[fcn(s) for s in string_list]。現在你只需要寫fcn

既然你已經知道的翻譯,我們可以把這個作爲

[s.translate(None, string.punctuation) for s in string_list] 
2

你有你的代碼一個錯字:

strings_modified.append.str(s).translate(None, string.punctuation) 

那就是你所得到的錯誤,你正試圖從叫做append的'builtin_function_or_method'調用一個名爲str的函數,它沒有這個方法,因爲它不能以這種方式工作!

你的代碼(可能取決於上下文)是:

strings_modified.append(str(s).translate(None, string.punctuation)) 
相關問題