【发布时间】:2021-12-02 01:56:17
【问题描述】:
对于一个作业,我正在创建函数 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: "')"
换行符真的让我很困惑,所以请耐心等待... 但总的来说,我应该在我的代码中进行哪些更改才能返回正确的字符串值?
【问题讨论】:
-
试着反过来想,即只保留字母表中的字符
-
你返回的是一个列表理解,所以它必须返回一个列表,而不是单个字符串。
-
你最后得到的错误似乎不是你发布的代码。
-
@Barmar 我的猜测是 OP 在文档字符串中添加了
remove_extraneous('boo!\n')。
标签: python string function replace list-comprehension