在字符串上使用 .translate() 去除数字 [Python 3] [英] Using .translate() on a string to strip digits [Python 3]

查看:41
本文介绍了在字符串上使用 .translate() 去除数字 [Python 3]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有字符串2okjser823ab".如何使用 .translate() 从字符串中删除所有数字?

我看到在 Python 2.x 中您可以执行类似 .translate(None, '0123456789') 的操作,但如果我在 Python 3 中尝试此操作,它会告诉我该方法只需要一个参数.

解决方案

看起来在 Python 3 中有点难;不知道为什么.

您可以这样做:

<预><代码>>>>导入字符串>>>翻译 = str.maketrans(string.ascii_letters, string.ascii_letters, string.digits)>>>"2okjser823ab".translate(translate)'okjserab'

您可能需要使用您期望的任何其他输入来扩展 string.ascii_letters(例如,string.ascii_letters + string.punctuation + string.whitespace).

我在 str.maketrans 的文档中没有清楚地找到它,但是如果您对前两个参数使用空字符串,则所有内容都将被映射为 1 到 1,但是删除部分(第三个参数)仍然发生:

<预><代码>>>>翻译 = str.maketrans("", "", string.digits)>>>"2eeŷýéeokjser823 ab.;\t".translate(translation)'eeŷýéeokjser ab.;\t'

Let's say I have the string '2okjser823ab'. How can I remove all the numbers from the string using .translate()?

I see that in Python 2.x you can do something like .translate(None, '0123456789') but if I try this in Python 3 it tells me that the method only takes one argument.

解决方案

It looks like it's a bit harder in Python 3; not sure why.

Here's what you can do:

>>> import string
>>> translation = str.maketrans(string.ascii_letters, string.ascii_letters, string.digits)
>>> "2okjser823ab".translate(translation)
'okjserab'

You may need to expand string.ascii_letters with whatever else you expect as input (string.ascii_letters + string.punctuation + string.whitespace, for example).

Edit: I can't find it clearly in the documentation for str.maketrans, but if you use an empty string for the first two arguments, everything will be mapped 1 to 1, but the deletion part (the third argument) still happens:

>>> translation = str.maketrans("", "", string.digits)
>>> "2eeŷýéeokjser823 ab.;\t".translate(translation)
'eeŷýéeokjser ab.;\t'

这篇关于在字符串上使用 .translate() 去除数字 [Python 3]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆