1

I'm fairly new to python (and this community), this is a question branching off of a question asked and answered from a long time ago from here

With a list like:

['hello', '...', 'h3.a', 'ds4,']

Creating a new list x with no punctuation (and deleting empty elements) would be:

x = [''.join(c for c in s if c not in string.punctuation) for s in x]
x = [s for s in x if s]
print(x)

Output:

['hello', 'h3a', 'ds4']

However, how would I be able to remove all punctuation only from the beginning and end of each element? I mean, to instead output this:

['hello', 'h3.a', 'ds4']

In this case, keeping the period in the h3a but removing the comma at the end of the ds4.

dl784
  • 61
  • 4

2 Answers2

3

You could use regular expressions. re.sub() can replace all matches of a regex with a string.

import re
X = ['hello', '.abcd.efg.', 'h3.a', 'ds4,']
X_rep = [re.sub(r"(^[^\w]+)|([^\w]+$)", "", x) for x in X] 
print(X_rep)
# Output: ['hello', 'abcd.efg', 'h3.a', 'ds4']

Explanation of regex: Try it

  • (^[^\w]+):
    • ^: Beginning of string
    • [^\w]+: One or more non-word characters
  • |: The previous expression, or the next expression
  • ([^\w]+$):
    • [^\w]+: One or more non-word characters
    • $: End of string
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
1
x = ['hello', '...', 'h3.a', 'ds4,']
x[0] = [''.join(c for c in s if c not in string.punctuation) for s in x][0]
x[(len(x)-1)] = [''.join(c for c in s if c not in string.punctuation) for s in x][(len(x)-1)]
x = [s for s in x if s]
print(x)
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Dash11235
  • 80
  • 7
  • 1
    Please see [this](/help/formatting) for formatting help. Please also take the [tour] and read [answer]. While code-only answers might answer the question, you could significantly improve the quality of your answer by providing context for your code, a reason for why this code works, and some references to documentation for further reading. From [answer]: _"Brevity is acceptable, but fuller explanations are better."_ Welcome to Stack Overflow! – Pranav Hosangadi Nov 09 '20 at 20:27