How to Delete Punctuation Marks in Python

When you're working with strings in Python, punctuation marks sometimes create problems, especially marks such as periods and backslashes that are normally used by computers as special characters. For your program to run properly, you can delete punctuation marks with the "re" module in Python. This will remove everything from a string except letters, numbers, underscores and spaces.

Instructions

    • 1

      Open the Python script that has a string from which you want to delete punctuation.

    • 2

      Type the following:

      import re, string
      s = "string to remove punctuation from"
      out = re.sub('[%s]' % re.escape(string.punctuation), '', s)

      Replace "string to remove punctuation from" with the actual string.

    • 3

      Save and close your Python script.

Related Searches:

References

Comments

Related Ads

Featured