简体   繁体   中英

AttributeError: 'int' object has no attribute 'replace'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM