rectangletangle
rectangletangle

Reputation: 52931

Finding the character occupying a particular index in a string

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'.

Upvotes: 0

Views: 8283

Answers (3)

PyNEwbie
PyNEwbie

Reputation: 4940

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

Upvotes: 0

NullUserException
NullUserException

Reputation: 85458

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

Upvotes: 4

Jim Brissom
Jim Brissom

Reputation: 32919

a = "Hello"
print a[0]
print a[4]

Upvotes: 4

Related Questions