[Python]_ Does python has string comprehension like list comprehension?

Viewed 1590

I am studying Python and I got curious about string formatting.

I learned that there is a list comprehension to manipulate or create a list in Python.

For example,

li1 = [i for i in rage(10)]
# this will create a list name with li1
# and li1 contains following:
print(li1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

So, my question is, if I have the code below, is there any solution to solve this? Like using list comprehension?

# The task I need to do is remove all the pucntuations from the string and replace it to empty string.

text = input() # for example: "A! Lion? is crying..,!" is given as input
punctuations = [",", ".", "!", "?"]
punc_removed_str = text.replace(p, "") for p in punctuations
# above line is what I want to do.. 

print(remove_punctuation) 
# Then result will be like below:
    # Output: A Lion is crying
2 Answers

Python already has a complete set of punctuations in the standard library.

from string import punctuation

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

Docs

So you can create a list from your given input which checks whether or not each characters from your input is in the punctuation string.

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

You can pass the resulting list in the built-in str.join method.

>>> "".join([char for char in text if char not in punctuation])
'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
Related