Home > OS >  Removing first and last punctuation from python
Removing first and last punctuation from python

Time:11-25

I have the following problem, I want to remove the punctuation marks at the beginning and at the end but leave the ones in between.
Example. \

[':Hamburger{', 'word>', 'don´t', 'isn´t,'] 

and this should turn

['Hamburger', 'word', 'don´t', 'isn´t']

So if anyone can help me, I would appreciate it

CodePudding user response:

You could use a regular expression for this. Just import re at the start of the file, then you could use the following line to replace all punctuation and the start or end of the line:

for el in list:
    el = re.sub("^[^\w\s]|[^\w\s]$", "", el)

CodePudding user response:

The string module has a predefined string of common punctuation characters:

>>> from string import punctuation as punct
>>> punct
'!"#$%&\'()* ,-./:;<=>?@[\\]^_`{|}~'

Which you can use in combination with str.strip to strip each of your strings:

>>> "<>.,.,.!TEST<>>..]}".strip(punct)
'TEST'

def make_pretty(word):
    from string import punctuation as punct
    return word.strip(punct)

words = [':Hamburger{', 'word>', 'don´t', 'isn´t,']

print(list(map(make_pretty, words)))

Output:

['Hamburger', 'word', 'don´t', 'isn´t']

That being said, string.punctuation is not exhaustive. The character ´, for example, is not present, and therefore wouldn't be stripped.

  • Related