tags:

views:

45

answers:

3

I have a the string 'Hello', I need to find out what characters occupy which indexes.

Pseudo-code:

string = 'Hello'
a = string.index(0)
b = string.index(4)
print a , b

a would be 'H' and b would be 'o'.

+2  A: 
a = "Hello"
print a[0]
print a[4]
Jim Brissom
+4  A: 

String (str) in Python is a sequence type, and thus can be accessed with []:

my_string = 'Hello'

a = my_string[0]
b = my_string[4]

print a, b # Prints H o

This means it also supports slicing, which is the standard way to get a substring in Python:

print my_string[1:3] # Prints el
NullUserException
In anticipation of the lack of Python experience in the guy asking this question, I might add that it might not be a good idea to name a variable after an existing module, `string` in this case.
Jim Brissom
@Jim a deprecated module nonetheless
NullUserException
A: 

I think he is asking for this

 for index,letter in enumerate('Hello'):
    print 'Index Position ',index, 'The Letter ', letter

And maybe we want to explore some data structures

so lets add a dictionary - I can do this lazily since I know that index values are unique

index_of_letters={}
for index,letter in enumerate('Hello'):
    index_of_letters[index]=letter
index_of_letters
PyNEwbie