AttributeError:"int"对象没有属性"replace" [英] AttributeError: 'int' object has no attribute 'replace'
问题描述
我想知道为什么在运行此代码时出现此错误:
# Ask user input
# Find out network device id for network device with ip or hostname, index 3 is device id
# In the loop until 'id' is assigned or user select 'exit'
id = ""
device_id_idx = 3
while True:
user_input = input('=> Select a number for the device from above to show IOS config:')
user_input= user_input.replace(" ","") # ignore space
if user_input.lower() == 'exit':
sys.exit()
if user_input.isdigit():
if int(user_input) in range(1,len(device_show_list)+1):
id = device_list[int(user_input)-1][device_id_idx]
break
else:
print ("Oops! number is out of range, please try again or enter 'exit'")
else:
print ("Oops! input is not a digit, please try again or enter 'exit'")
# End of while loop
输出错误:
user_input= user_input.replace(" ","") # ignore space
AttributeError: 'int' object has no attribute 'replace'
该代码应接受输入并返回信息.预先感谢!
如果您使用的是Python3.x,则input
将返回一个字符串,您可以尝试调试代码以检查user_input
或
print(type(user_input))
如果您使用的是Python2.x input
,可能不是代码的好方法
因为input
函数会评估您的输入.如果输入是1 2
,则将得到SyntaxError: invalid syntax
,如果输入是1
,则将得到int
对象,这就是您收到错误的原因. /p>
我建议使用raw_input
,因为raw_input
完全接受用户键入的内容,并将其作为字符串传递回去.
您可以阅读此
希望这会有所帮助.
I am wondering why I have this error when I run this code:
# Ask user input
# Find out network device id for network device with ip or hostname, index 3 is device id
# In the loop until 'id' is assigned or user select 'exit'
id = ""
device_id_idx = 3
while True:
user_input = input('=> Select a number for the device from above to show IOS config:')
user_input= user_input.replace(" ","") # ignore space
if user_input.lower() == 'exit':
sys.exit()
if user_input.isdigit():
if int(user_input) in range(1,len(device_show_list)+1):
id = device_list[int(user_input)-1][device_id_idx]
break
else:
print ("Oops! number is out of range, please try again or enter 'exit'")
else:
print ("Oops! input is not a digit, please try again or enter 'exit'")
# End of while loop
output error:
user_input= user_input.replace(" ","") # ignore space
AttributeError: 'int' object has no attribute 'replace'
This code is supposed to accept an input and return information. Thanks in advance!
If you're using Python3.x input
will return a string,you can try to debug your code to check the type of user_input
or
print(type(user_input))
If you're using Python2.x input
maybe is not a good way for your code
because input
function evaluates your input.If your input is 1 2
you will get SyntaxError: invalid syntax
,and if your input is 1
,and it will get int
object,this is why you got the error.
I suggest raw_input
because raw_input
takes exactly what the user typed and passes it back as a string.
You can read this
Hope this helps.
这篇关于AttributeError:"int"对象没有属性"replace"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!