È necessario creare una tabella di conversione utilizzando maketrans
passata al metodo str.translate
.
In Python 3.1 e successivi, maketrans
ora è un static-method on the str
type, in modo da poter utilizzare per creare una traduzione di ogni punteggiatura che si desidera None
.
import string
# Thanks to Martijn Pieters for this improved version
# This uses the 3-argument version of str.maketrans
# with arguments (x, y, z) where 'x' and 'y'
# must be equal-length strings and characters in 'x'
# are replaced by characters in 'y'. 'z'
# is a string (string.punctuation here)
# where each character in the string is mapped
# to None
translator = str.maketrans('', '', string.punctuation)
# This is an alternative that creates a dictionary mapping
# of every character from string.punctuation to None (this will
# also work)
#translator = str.maketrans(dict.fromkeys(string.punctuation))
s = 'string with "punctuation" inside of it! Does this work? I hope so.'
# pass the translator to the string's translate method.
print(s.translate(translator))
Questo stamperà:
string with punctuation inside of it Does this work I hope so
perfetto, funziona eccellente! – cybujan
(esempio @birryree (http://stackoverflow.com/a/34294398/1656850) chiede di non essere d'accordo con il tuo editto deprecazione su string.translate ;-) – boardrider
Hai ragione. Ho frainteso la documentazione su questo punto. Solo la firma della chiamata è cambiata: str.translate prende solo una tabella come parametro e non più deletechars (come si vede nella risposta di birryree). Modificherò la mia risposta di conseguenza. – elzell