Python 有像列表理解那样的字符串理解吗?

问题描述 投票:0回答:2

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"
python string list-comprehension
2个回答
4
投票

没有字符串理解,但是您可以使用生成器表达式,它在列表理解中使用,在

join()

text = ''.join(x for x in text if x not in punctuations)
print(text) # A Lion is crying

4
投票

Python 标准库中已经有一套完整的标点符号。

from string import punctuation

punctuation
返回字符串 !"#$%&'()*+,-./:;<=>?@[]^_`{|}~.

文档

因此,您可以根据给定的输入创建一个列表,检查输入中的每个字符是否在

punctuation
字符串中。

>>> [char for char in text if char not in punctuation]
['A', ' ', 'L', 'i', 'o', 'n', ' ', 'i', 's', ' ', 'c', 'r', 'y', 'i', 'n', 'g']

您可以在内置

str.join
方法中传递结果列表。

>>> "".join([char for char in text if char not in punctuation])
'A Lion is crying'
© www.soinside.com 2019 - 2024. All rights reserved.