我希望有人可以帮助我。我一整天都在这么做。我想让用户输入一个电话号码,其中可以包含"800-FLOWERS"
等文字。我想打印输出只是数字,但我收到以下错误:
TypeError: Can't convert 'int' object to str implicitly
这是我的代码:
keypad = {'a':2, 'A':2, 'b':2, 'B':2, 'c':2, 'C':2,
'd':3, 'D':3, 'e':3, 'E':3, 'f':3, 'F':3,
'g':4, 'G':4, 'h':4, 'H':4, 'i':4, 'I':4,
'j':5, 'J':5, 'k':5, 'K':5, 'l':5, 'L':5,
'm':6, 'M':6, 'n':6, 'N':6, 'o':6, 'O':6,
'p':7, 'P':7, 'q':7, 'Q':7, 'r':7, 'R':7, 's':7, 'S':7,
't':8, 'T':8, 'u':8, 'U':8, 'v':8, 'V':8,
'w':9, 'W':9, 'x':9, 'X':9, 'y':9, 'Y':9, 'z':9, 'Z':9} # Create keypad dict
phone_num = input('Enter a phone number: ')
for key, value in keypad.items():
phone_num = (phone_num.upper().replace(key, value))
phone_num = str(phone_num)
print('The number entered is: %s'% phone_num)
答案 0 :(得分:5)
您正在尝试将dbms_output.put_line('1 2 3 4 5 6 7 8 9 ')
dbms_output.put_line('1 2 3 4 5 6 7 8 9 ')
dbms_output.put_line('1 2 3 4 5 6 ');
与string
类型连接起来,这是不允许的。你是在这一行做的:
int
最终,您在替换时所做的是尝试将phone_num = (phone_num.upper().replace(key, value))
类型放入int
。要解决此问题,请在string
上投射str
:
value
之后不需要您使用该行,因此您可以将其删除:phone_num = (phone_num.upper().replace(key, str(value)))
要演示确切的错误,请看:
phone_num = str(phone_num)
此外,将你的最后一个>>> s = "abc"
>>> s = s.replace('a', 4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
放在你的循环之外,否则它将在每次迭代中打印出来。
修复错误后,代码会按原样运行:
print
您可以考虑采用稍微不同的方式。而不是遍历您的Enter a phone number: 800-FLOWERS
The number entered is: 800-3569377
for key, value in keypad.items():
phone_num = (phone_num.upper().replace(key, str(value)))
print('The number entered is: %s'% phone_num)
字典,而是遍历字符串,检查您是否有字母字符。如果这样做,那么在字典中查找以获取值并转换为字符串,否则只需将“字符”添加到新字符串中。此外,这也适用于您的原始解决方案,因为您已经转换为keypad
,您的词典可以简化为仅一个大小写:
upper
答案 1 :(得分:0)
#Switch from this
phone_num = (phone_num.upper().replace(key, value))
phone_num = str(phone_num)
#To this
phone_num = str(phone_num)
phone_num = (phone_num.upper().replace(key, value))
#Or even shorter, this
phone_num = str(phone_num.upper().replace(key, value))
答案 2 :(得分:0)
如果你有两种组合,你就不需要鞋面了,你应该做一个raw_input来获取python2中的字符串
keypad = {'a':2, 'A':2, 'b':2, 'B':2, 'c':2, 'C':2,
'd':3, 'D':3, 'e':3, 'E':3, 'f':3, 'F':3,
'g':4, 'G':4, 'h':4, 'H':4, 'i':4, 'I':4,
'j':5, 'J':5, 'k':5, 'K':5, 'l':5, 'L':5,
'm':6, 'M':6, 'n':6, 'N':6, 'o':6, 'O':6,
'p':7, 'P':7, 'q':7, 'Q':7, 'r':7, 'R':7, 's':7, 'S':7,
't':8, 'T':8, 'u':8, 'U':8, 'v':8, 'V':8,
'w':9, 'W':9, 'x':9, 'X':9, 'y':9, 'Y':9, 'z':9, 'Z':9} # Create keypad dict
phone_num = raw_input('Enter a phone number: ')
for key, value in keypad.items():
phone_num = phone_num.replace(key,str(value))
print('The number entered is: %s' % phone_num)