我是一个Python新手。
为什么this在Python 3.1中不起作用?
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab);
当我执行上面的代码时,我得到以下代码:
Traceback (most recent call last):
File "<pyshell#119>", line 1, in <module>
transtab = maketrans(intab, outtab)
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/string.py", line 60, in maketrans
raise TypeError("maketrans arguments must be bytes objects")
TypeError: maketrans arguments must be bytes objects
“必须是字节对象”是什么意思?如果有可能,有人可以帮助发布Python 3.1的工作代码吗?
答案 0 :(得分:33)
当bytes.maketrans()
更简单时,您无需使用str
,并且无需使用'b'前缀:
print("Swap vowels for numbers.".translate(str.maketrans('aeiou', '12345')))
答案 1 :(得分:16)
通过阅读Python 2文档,停止尝试学习Python 3.
intab = 'aeiou'
outtab = '12345'
s = 'this is string example....wow!!!'
print(s.translate({ord(x): y for (x, y) in zip(intab, outtab)}))
答案 2 :(得分:11)
字符串不字节。
这是Python 3中的一个简单定义。
字符串是Unicode(不是字节)Unicode字符串使用"..."
或'...'
字节是字节(不是字符串)字节字符串使用b"..."
或b'...'
。
使用b"aeiou"
创建由某些字母的ASCII代码组成的字节序列。
答案 3 :(得分:6)
在Python 3中,string.maketrans()
函数已弃用,并被新的静态方法bytes.maketrans()
和bytearray.maketrans()
取代。
此更改解决了字符串模块支持哪些类型的混淆。
现在str
,bytes
和bytearray
每个都有自己的maketrans
和translate
方法,其中包含相应类型的中间转换表。
答案 4 :(得分:5)
"this is string example....wow!!!".translate(str.maketrans("aeiou","12345"))
这个工作,没有额外的字节转换。 我不知道为什么要使用byte而不是str。
答案 5 :(得分:2)
如果你绝对坚持使用8位字节:
>>> intab = b"aeiou"
>>> outtab = b"12345"
>>> trantab = bytes.maketrans(intab, outtab)
>>> strg = b"this is string example....wow!!!";
>>> print(strg.translate(trantab));
b'th3s 3s str3ng 2x1mpl2....w4w!!!'
>>>
答案 6 :(得分:0)
嘿,这是一个简单的衬垫,对我来说非常合适
import string
a = "Learning Tranlate() Methods"
print (a.translate(bytes.maketrans(b"aeiou", b"12345")))*
输出 ::::
L21rn3ng Tr1nl1t2()M2th4ds
答案 7 :(得分:0)
以下是在Python 2或3中执行翻译和删除的示例:
import sys
DELETE_CHARS = '!@#$%^*()+=?\'\"{}[]<>!`:;|\\/-,.'
if sys.version_info < (3,):
import string
def fix_string(s, old=None, new=None):
if old:
table = string.maketrans(old, new)
else:
table = None
return s.translate(table, DELETE_CHARS)
else:
def fix_string(s, old='', new=''):
table = s.maketrans(old, new, DELETE_CHARS)
return s.translate(table)
答案 8 :(得分:0)
maketrans是一个字符串函数
使用以下逻辑来使用maketrans进行翻译
print('maketrans' , '& translate')
intab = "aeiou"
outtab = "12345"
str = "Fruits are delicious and healthy!!!"
trantab = str.maketrans(intab, outtab)
print (str.translate(trantab))
答案 9 :(得分:-1)
这是我最后发布的Python(3.1)代码,仅供参考:
"this is string example....wow!!!".translate(bytes.maketrans(b"aeiou",b"12345"))
简短而甜蜜,喜欢它。