Dev*_*oki 7 python string list-comprehension
Python 是否有一个类似于列表理解的结构来创建字符串,即“字符串理解”?
我需要做的任务是删除字符串中的所有标点符号。
def remove_punctuation(text: str) -> str:
punctuations = [",", ".", "!", "?"]
# next line is what I want to do
result = text.replace(p, "") for p in punctuations
return result
assert remove_punctuation("A! Lion?is. crying!..") == "A Lion is crying"
Run Code Online (Sandbox Code Playgroud)
没有字符串理解,但是您可以使用生成器表达式,它在列表理解中使用,在内部join()
text = ''.join(x for x in text if x not in punctuations)
print(text) # A Lion is crying
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4460 次 |
| 最近记录: |