21

I know how to remove all the punctuation in a string.

import string

s = '.$ABC-799-99,#'

table = string.maketrans("","") # to remove punctuation
new_s = s.translate(table, string.punctuation)

print(new_s)
# Output
ABC79999

How do I strip all leading and trailing punctuation in Python? The desired result of '.$ABC-799-99,#' is 'ABC-799-99'.

SparkAndShine
  • 17,001
  • 22
  • 90
  • 134

1 Answers1

36

You do exactly what you mention in your question, you just str.strip it.

from string import punctuation
s = '.$ABC-799-99,#'

print(s.strip(punctuation))

Output:

 ABC-799-99

str.strip can take multiple characters to remove.

If you just wanted to remove leading punctuation you could str.lstrip:

s.lstrip(punctuation)

Or rstrip any trailing punctuation:

 s.rstrip(punctuation)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Thx. If I'd keep `$`, `s.strip(string.punctuation.replace('$', ''))`, is it a better way? – SparkAndShine May 14 '16 at 00:58
  • 1
    @sparkandshine, no worries,i think `.punctuation.replace('$', '')` is pretty good, the other option is manually creating a string of punctuation characters minus $ and using that which I think would be a lot more arduous. – Padraic Cunningham May 14 '16 at 01:01