当前位置:  首页>> 技术小册>> Python合辑4-130个字符串操作示例

从 Python 中的字符串中去除标点符号

  1. import string
  2. import re
  3. # Example 1
  4. s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
  5. out = re.sub(r'[^\w\s]', '', s)
  6. print(out)
  7. # Example 2
  8. s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
  9. for p in string.punctuation:
  10. s = s.replace(p, "")
  11. print(s)
  12. # Example 3
  13. s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
  14. out = re.sub('[%s]' % re.escape(string.punctuation), '', s)
  15. print(out)

Output:

  1. Ethnic 279 Responses 3 2016 Census 25 Sample
  2. Ethnic 279 Responses 3 2016 Census 25 Sample
  3. Ethnic 279 Responses 3 2016 Census 25 Sample