-4

How do I remove punctuation from a string in python? I followed the approach that someone posted on Stackoverflow, but it is not working.

punctuation = ['(', ')', '?', ':', ':', ',', '.', '!', '/', '"', "'"]

str = input("Hi, my name is Yael Shapiro!")

for i in punctuation:
    str = str.replace(i,"")

print(str)
Sumner Evans
  • 8,302
  • 5
  • 27
  • 44
Yjell
  • 21
  • 1
  • 1
  • 3
  • 3
    *"not working"* is a completely useless problem description – jonrsharpe Nov 02 '16 at 22:55
  • Also, do not use built-ins as variable names. `str` is a built-in, and you will certainly run in to problems shadowing built-in names. – idjaw Nov 02 '16 at 22:59

1 Answers1

1

I find using a combination of gencomp and "".join() works well:

>>> import string
>>> s = "Does this string. Have punctuation?"
>>> 
>>> "".join((char for char in s if char not in string.punctuation))
'Does this string Have punctuation'
>>> 

And as a side note, do not use str as an identifier as it already has a meaning in the Python language.

The reason that your code is not working, is probably because you're misunderstanding what input() does. input() simply gets input from the user and returns the input. It looks to me that all you want to do is have a string, in which just do: sstr = "Hi, my name is Yael Shapiro!"

Community
  • 1
  • 1
Christian Dean
  • 19,561
  • 6
  • 42
  • 71
  • Thanks so much! So I am changing it to the following, but it is still not removing the punctuation: import string sstr = "Hi, my name is Yael Shapiro!" "".join((char for char in sstr if char not in string.punctuation)) print(sstr) – Yjell Nov 03 '16 at 00:13
  • You need to assign the value of `sstr` to your stripped string. In other words, use `sstr = ".join((char for char in sstr if char not in string.punctuation)) ` instead of `".join((char for char in sstr if char not in string.punctuation)) `. – Christian Dean Nov 03 '16 at 00:19