error with string (beginner)

Jason gaudetteje at gmail.com
Sun Jun 25 11:13:35 EDT 2006


I believe what you are trying to do is something like the following.

[code]
def isIntLike(x):
	try:    int(x)
	except: return False
	else:   return True

something = raw_input("Enter something and I will tell you the type: ")

if isIntLike(something):	print "I am an int"
elif isinstance(something, type('')):	print "I am a string"
else:	print "I am an impostor!"
[/code]

Note that you should be using raw_input() rather than input().  The
former always returns a string.  The latter tries to execute the input,
hence your error message.

Also note that everything input on the command line is a string,
regardless of what you type.  If you want type checking, use C++ or
java.  If you want to check for anything more than IntLike strings, you
should consider using regular expressions through the 're' package.
For user-defined types, use 'isinstance(something, class object)' to
check for a type.

Lastly, you may be interested in the 'getopt' module, which handles
command line arguments (as opposed to prompting user for input)
automatically.   See here:
http://python.active-venture.com/lib/module-getopt.html

Check out the Python Cookbook for lots of good examples:
http://aspn.activestate.com/ASPN/Cookbook/Python

HTH,

Jay



Alex Pavluck wrote:
> Hello. I get the following error with the following code.  Is there
> something wrong with my Python installation?
>
> code:
> import types
> something = input("Enter something and I will tell you the type: ")
>
> if type(something) is types.IntType:
>     print "you entered an integer"
> elif type(something) is types.StringType:
>     print "you entered a string"
> 
> error:
> String: Source for exec/eval is unavailable




More information about the Python-list mailing list