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

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)

Guy*_*Guy 4

没有字符串理解,但是您可以使用生成器表达式,它在列表理解中使用,在内部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)

  • 小更正:括号内的是生成器表达式,而不是列表理解。 (2认同)