對于分配,我正在創建函式 remove_extraneous,旨在接收任何字串并回傳字母表中僅包含字母的字串。到目前為止,這是我的嘗試:
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def remove_extraneous(text):
'''
Description:
Examples:
>>> remove_extraneous('test !')
>>> remove_extraneous('code??')
'''
return ([text.replace(i, "") for i in text if i not in alphabet])
我的例子回傳:
Examples:
>>> remove_extraneous('test !')
['test!', 'test ']
>>> remove_extraneous('code??')
['code', 'code']
到目前為止,這很好,因為它有點作業,但并不完全。它應該回傳:
Examples:
>>> remove_extraneous('test !')
'test'
>>> remove_extraneous('code??')
'code'
另外,我的老師的例子說這個例子應該回傳這個:
>>> remove_extraneous('boo!\n')
'boo'
但是當我嘗試時,我的回傳以下錯誤:
raise ValueError('line %r of the docstring for %s has '
ValueError: line 10 of the docstring for __main__.remove_extraneous has inconsistent leading whitespace: "')"
換行符真的讓我感到困惑,所以請耐心等待...但總的來說,我應該在代碼中更改什么才能回傳正確的字串值?
uj5u.com熱心網友回復:
你可以大大簡化這個。確保回傳 a str,而不是 a list:
from string import ascii_lowercase
alphabet = set(ascii_lowercase)
def remove_extraneous(text):
return "".join(c for c in text if c in alphabet)
>>> remove_extraneous('test !')
'test'
>>> remove_extraneous('code??')
'code'
>>> remove_extraneous('boo!\n')
'boo'
一些檔案:
string.ascii_lowercasestr.join
uj5u.com熱心網友回復:
這就是您的代碼不起作用的原因。
當你這樣做時:
[text.replace(i, "") for i in text if i not in alphabet]
如果字母不是字母表,您會生成一個串列,每個字母在文本中包含一個專案。
對'abc'您來說意味著什么都沒有,因為'abc!'您將擁有['abc']一個無效字符,因為'abc!!!!!!!!'您將獲得與感嘆號一樣多的專案。
第二想。使用replace和回圈字符效率不高,因為您將決議完整字串的次數與您有字符的次數一樣多,因此您將粗略地決議它的長度的平方。這意味著您的代碼將變得非常緩慢非常快。
正確的做法是將字符一一檢查,如果在白名單中,則保留:
[char for char in text if char in alphabet]
然后您獲得一個串列,您需要通過加入字符將其轉換回字串:
''.join(char for char in text if char in alphabet)
uj5u.com熱心網友回復:
我建議使用re正則運算式模塊:
import re
non_letters = re.compile('[^A-Za-z]')
def remove_extraneous(text):
return non_letters.sub('', text)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317704.html
上一篇:如何在字串中的特定文本后插入值
