Best way to strip punctuation from a string

前端 未结 26 1920
日久生厌
日久生厌 2020-11-21 05:39

It seems like there should be a simpler way than:

import string
s = \"string. With. Punctuation?\" # Sample string 
out = s.translate(string.maketrans(\"\",\         


        
26条回答
  •  我寻月下人不归
    2020-11-21 05:58

    #FIRST METHOD
    #Storing all punctuations in a variable    
    punctuation='!?,.:;"\')(_-'
    newstring='' #Creating empty string
    word=raw_input("Enter string: ")
    for i in word:
         if(i not in punctuation):
                      newstring+=i
    print "The string without punctuation is",newstring
    
    #SECOND METHOD
    word=raw_input("Enter string: ")
    punctuation='!?,.:;"\')(_-'
    newstring=word.translate(None,punctuation)
    print "The string without punctuation is",newstring
    
    
    #Output for both methods
    Enter string: hello! welcome -to_python(programming.language)??,
    The string without punctuation is: hello welcome topythonprogramminglanguage
    

提交回复
热议问题