Does Python have a construct analogue to list comprehension for creating strings, a "string comprehension"?
The task I need to do is remove all punctuation from the string.
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"
There isn't string comprehension, however you can use generator expression, which is used in list comprehension, inside join()
text = ''.join(x for x in text if x not in punctuations)
print(text) # A Lion is crying
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With