Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have String Comprehension like List Comprehension?

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"
like image 420
DevThinKoki Avatar asked Aug 01 '26 01:08

DevThinKoki


1 Answers

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
like image 164
Guy Avatar answered Aug 02 '26 14:08

Guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!