我是编程新手...我的代码非常简单。假设我的电话号码是“ 123”,那么我想输入“ abc”。请检查我在哪里错了
def number2char(number):
search_array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
replace_array = ["a", "b", "c", "d", "d", "e", "f", "g", "h", "i"]
num_2_char = number.replace(search_array, replace_array);
return num_2_char;
我在这里遇到错误
num_2_char = number.replace(search_array,replace_array); TypeError:需要一个字符缓冲区对象
请帮助我...
答案 0 :(得分:2)
问题是str.replace
用替换子字符串替换了一个子字符串。这就是错误的含义:它想要一个子字符串,并且您给了它一个单独的字符列表。
您可以遍历替换对,对每个替换对调用replace
:
>>> s = '123'
>>> for search, replace in zip(search_array, replace_array):
... s = s.replace(search, replace)
>>> s
'abc'
或者您可以只使用str.translate
,尽管需要一些设置,但实际上 会做{em> :
>>> search_array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
>>> replace_array = ["a", "b", "c", "d", "d", "e", "f", "g", "h", "i"]
>>> trans = str.maketrans(dict(zip(search_array, replace_array)))
>>> '123'.translate(trans)
'abc'
或者,或者更具可读性:
>>> search = "1234567890"
>>> replace = "abcddefghi"
>>> trans = str.maketrans(search, replace)
>>> '123'.translate(trans)
'abc'
顺便说一句,如果不是故意连续两次指定d
,则这样指定字母可能会更清楚(更难打错!)
>>> replace = string.ascii_lowercase[:10]
答案 1 :(得分:1)
您可以改用字典。这里有一些步骤:
'123'
),但是没有理由不能使该函数同时接受数字和字符串输入。join()
才能将所有字符重新组合成一个字符串。一种方法如下:
def number2char(number):
search_array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
replace_array = ["a", "b", "c", "d", "d", "e", "f", "g", "h", "i"]
replace_dict = dict(zip(search_array, replace_array))
num_2_char = ''.join([replace_dict.get(char, '_')
for char in str(number)])
return num_2_char
a = number2char(123)
在这种情况下,我使用了replace_dict.get(str(item), '_')
,因此,如果有人输入的内容不在replace_dict
中,则代码不会崩溃。相反,他们只是回到下划线。可能有更好的方法来处理该问题,但是它比尝试以replace_dict[item]
的身份访问字典更为安全。
答案 2 :(得分:-1)
def number2char(number):
search_array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
replace_array = ["a", "b", "c", "d", "d", "e", "f", "g", "h", "i"]
num_2_char=''
for i in number:
num_2_char += replace_array[search_array.index(i)]
return num_2_char;