擅长:python、mysql、java
<p><code>str.translate</code>需要一个<code>dict</code>来将unicode序号映射到其他unicode oridinals(或者<code>None</code>如果要删除该字符)。你可以这样创建它:</p>
<pre><code>old_string = "file52.txt"
to_remove = "0123456789"
table = {ord(char): None for char in to_remove}
new_string = old_string.translate(table)
assert new_string == "file.txt"
</code></pre>
<p>然而,通过使用<code>str.maketrans</code>函数,有一种更简单的方法来生成表。它可以包含各种参数,但您需要三个参数的形式。我们忽略前两个参数,因为它们用于将字符映射到其他字符。第三个参数是要删除的字符。</p>
<pre><code>old_string = "file52.txt"
to_remove = "0123456789"
table = str.maketrans("", "", to_remove)
new_string = old_string.translate(table)
assert new_string == "file.txt"
</code></pre>