“表"是什么意思在string.translate 函数中是什么意思? [英] What does "table" in the string.translate function mean?

查看:111
本文介绍了“表"是什么意思在string.translate 函数中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浏览string.translate 函数表示:

<块引用>

从 s 中删除所有在 deletechars 中的字符(如果存在),然后使用 table 转换字符,table 必须是一个 256 字符的字符串,给出每个字符值的转换,按其序数索引.如果 table 为 None,则只执行字符删除步骤.

  • table 在这里是什么意思?它可以是包含映射的 dict 吗?
  • 必须是 256 个字符的字符串"是什么意思?
  • 表格可以手动制作还是通过自定义函数制作,而不是string.maketrans?

我尝试使用该功能(下面的尝试)只是为了看看它是如何工作的,但未能成功使用它.

<预><代码>>>>"abcabc".translate("abcabc",{ord("a"): "d", ord("c"): "x"})回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中ValueError: 转换表的长度必须为 256 个字符

<预><代码>>>>"abcabc".translate({ord("a"): ord("d"), ord("c"): ord("x")}, "b")回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:应为字符缓冲区对象

<预><代码>>>>"abc".translate({"a": "d", "c": "x"}, ["b"])回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:应为字符缓冲区对象

我在这里遗漏了什么?

解决方案

这取决于您使用的 Python 版本.

在 Python 2.x 中.该表是 256 个字符的字符串.可以使用 string.maketrans 创建:><预><代码>>>>导入字符串>>>tbl = string.maketrans('ac', 'dx')>>>"abcabc".translate(tbl)'dbxdbx'

在 Python 3.x 中,该表是 unicode 序数到 unicode 字符的映射.

<预><代码>>>>"abcabc".translate({ord('a'): 'd', ord('c'): 'x'})'dbxdbx'

Going through the string.translate function which says:

Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.

  • What does table mean here? Can it be a dict containing the mapping?
  • What does "must be a 256-character string" mean?
  • Can the table be made manually or through a custom function instead of string.maketrans?

I tried using the function (attempts below) just to see how it worked but wasn't successfully able to use it.

>>> "abcabc".translate("abcabc",{ord("a"): "d", ord("c"): "x"})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: translation table must be 256 characters long

>>> "abcabc".translate({ord("a"): ord("d"), ord("c"): ord("x")}, "b")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object

>>> "abc".translate({"a": "d", "c": "x"}, ["b"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object

What am I missing here?

解决方案

It depends on Python version you are using.

In Python 2.x. The table is 256-characters string. It can be created using string.maketrans:

>>> import string
>>> tbl = string.maketrans('ac', 'dx')
>>> "abcabc".translate(tbl)
'dbxdbx'

In Python 3.x, the table is mapping of unicode ordinals to unicode characters.

>>> "abcabc".translate({ord('a'): 'd', ord('c'): 'x'})
'dbxdbx'

这篇关于“表"是什么意思在string.translate 函数中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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