Musisz utworzyć tabelę translacji za pomocą maketrans
, którą przekazujesz do metody str.translate
.
W języku Python 3.1 i nowszym maketrans
jest teraz static-method on the str
type, więc można go użyć do utworzenia tłumaczenia każdej interpunkcji, która ma być 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))
Powinno to wyjście:
string with punctuation inside of it Does this work I hope so
idealny, działa rewelacyjnie! – cybujan
(przykład @birryree (http://stackoverflow.com/a/34294398/1656850) prosi, aby nie zgadzać się z edycją deprecation na string.translate ;-) – boardrider
Masz rację. Źle zrozumiałem dokumentację na ten temat. Zmienił się tylko podpis wywołania: str.translate przyjmuje tylko tabelę jako parametr i nie usuwa już deletechar (jak widać w odpowiedzi birryree). Odpowiednio edytuję swoją odpowiedź. – elzell