9

For example:

asking="hello! what's your name?"

Can I just do this?

asking.strip("!'?")
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Wuchun Aaron
  • 289
  • 3
  • 4
  • 11
  • 2
    Have you looked at http://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python ? – Garrett Hyde Apr 17 '13 at 03:34

4 Answers4

22

A really simple implementation is:

out = "".join(c for c in asking if c not in ('!','.',':'))

and keep adding any other types of punctuation.

A more efficient way would be

import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)

Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python

Community
  • 1
  • 1
15
import string

asking = "".join(l for l in asking if l not in string.punctuation)

filter with string.punctuation.

thkang
  • 11,215
  • 14
  • 67
  • 83
0

This works, but there might be better solutions.

asking="hello! what's your name?"
asking = ''.join([c for c in asking if c not in ('!', '?')])
print asking
marcin_koss
  • 5,763
  • 10
  • 46
  • 65
0

Strip won't work. It only removes leading and trailing instances, not everything in between: http://docs.python.org/2/library/stdtypes.html#str.strip

Having fun with filter:

import string
asking = "hello! what's your name?"
predicate = lambda x:x not in string.punctuation
filter(predicate, asking)
Brenden Brown
  • 3,125
  • 1
  • 14
  • 15
  • .It is important to wrap `list()` around the entire `filter()` function if you're using Python 3.x, as many built-in functions no longer return `lists` but special `iterable` objects. Also, you seem to have overlooked putting `input` (or `raw_input` for Python 2.x) around the string in the second line, and you should have put something like `asking = ...` for the final line. – SimonT Apr 17 '13 at 03:45
  • 1
    Looks like this approach is discouraged in 3.x: http://stackoverflow.com/questions/13638898/how-to-use-filter-map-and-reduce-in-python-3-3-0 – Brenden Brown Apr 17 '13 at 03:49
  • `filter` is ugly and slow when you have to use a `lambda` with it, unfortunately your alternative is `''.join(ifilterfalse(partial(contains, punctuation), asking))` – jamylak Apr 17 '13 at 05:03