Your real question is "How to map strings to numbers in Python" (or vice-versa). As the current title may be misleading, lets first address it for folks coming over "how to compare strings and numbers": unlike popular script languages Python will not make automatic type castings. For example, in Javascript you can do this:
>>> 5 == '5'
true
But in Python it is False:
>>> 5 == '5'
False
You must cast both values to the same type (for example string
or int
) explicitly if you expect them to be of different types:
>>> str(5) == str('5')
True
Now lets get back to your real question. As @GarethLatty commented:
name1
, name2
is a really common anti-pattern. Use a data structure (list, dict, etc...) instead. This kind of problem becomes trivial too.
Two of the basic container data types in Python are the list
and the dict
.
Using a list:
>>> name_list = ['rock', 'paper', 'scissors', 'lizard', 'spock']
>>> name_list.index('spock')
4
List indexes are zero-based:
>>> name_list[0]
'rock'
Using a dict you can associate arbitrary numbers to strings:
>>> name_dict = {'rock': 1, 'paper': 2, 'scissors': 3, 'lizard': 4, 'spock': 5}
>>> name_dict['spock']
5
If the value is not present in the list, the index
method will raise a ValueError
exception. In Python it is common to surround this kind of expression with a try
block (like commented by icktoofay):
>>> name = 'kirk'
>>> try:
... name_list.index(name)
... except ValueError:
... print('{} is not a valid name.'.format(name))
...
kirk is not a valid name.
This programming style is very popular. Using a dict
, the exception you have to watch for is KeyError
:
>>> name_dict['kirk']
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
KeyError: 'kirk'
If you are starting with Python, the REPL (read-eval-print loop, the Python prompt) is your best friend. Just explore anything using the help
and dir
built-in functions:
>>> dir(name_dict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__',
'__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__',
'__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key',
'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop',
'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys',
'viewvalues']
>>> help(name_dict.keys)
Help on built-in function keys:
keys(...)
D.keys() -> list of D's keys
>>>