Python报错TypeError: 'str' object is not callable,在线方案无效求助
Hey there! I’ve run into this exact error before, so let’s break it down and fix it quickly.
What’s causing this error?
The error TypeError: 'str' object is not callable on line 7 means you’ve accidentally overwritten Python’s built-in input() function with a string variable somewhere.
For example, if you ran something like input = "New York" earlier in your session (either in the same script or in an interactive shell/Jupyter notebook), you turned the input name into a string. When your code tries to call input('Enter location: '), it’s trying to run that string like a function—which doesn’t work!
How to fix it
- Check for variable name conflicts: Scan through your code (and any previous code cells if you’re using a notebook) to see if you’ve assigned a value to a variable named
input. Rename that variable to something else (likeuser_inputorlocation_input) to avoid clashing with the built-in function. - Reset your Python environment: If you’re working in an interactive shell or Jupyter notebook, restart the kernel/shell. This will restore the original built-in
input()function, since the overwrite only exists in your current session. - Temporary workaround (not ideal, but works): If you can’t restart right now, you can explicitly call the built-in version like this:
But again, renaming conflicting variables is the cleaner long-term fix.input_str = __builtins__.input('Enter location: ')
Verifying your code
Looking at the full code you shared, there’s no direct overwrite of input in the script itself. That means the issue is almost certainly from a previous line of code you ran in the same session that used input as a variable name. Restarting your environment should get things working again.
Here’s your original code with a note to avoid variable name clashes:
import urllib.request, urllib.parse, urllib.error import xml.etree.ElementTree as ET serviceurl = 'http://maps.googleapis.com/maps/api/geocode/xml?' while True: # Make sure you haven't used 'input' as a variable name elsewhere! input_str = input('Enter location: ') if len(input_str) < 1: break url = serviceurl + urllib.parse.urlencode({'address': input_str}) print('Retrieving', url) uh = urllib.request.urlopen(url) data = uh.read() print('Retrieved', len(data), 'characters') print(data.decode()) tree = ET.fromstring(data) results = tree.findall('result') lat = results[0].find('geometry').find('location').find('lat').text lng = results[0].find('geometry').find('location').find('lng').text location = results[0].find('formatted_address').text print('lat', lat, 'lng', lng) print(location)
Give these steps a try—your code should run as expected once the input function is no longer overwritten!
内容的提问来源于stack exchange,提问作者CathyQian

