2

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!

kbunarjo
  • 1,277
  • 2
  • 11
  • 27
Lawrence Orewa
  • 23
  • 1
  • 1
  • 4
  • 1
    You're using Python 2.x, where `input()` evaluates what the user types as a Python expression. Since the user has typed an integer, you get an `int` rather than a `str`. Use `raw_input()` instead and you'll always get a string. – kindall Dec 30 '16 at 03:46
  • I would encourage you to post a full code with import statements. – Eddie Dec 30 '16 at 03:46

1 Answers1

0

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.

Community
  • 1
  • 1
McGrady
  • 10,869
  • 13
  • 47
  • 69