johndoe12345
johndoe12345

Reputation: 421

Can someone explain this simple syntax to me

can someone give me a very quick explanation of what this code does :

  for j in range(len(word)):
        if word[j] in key:
            newString = newString+key[word[j]]

Obviously the code above makes no sense but i really just want to know what putting j in the brackets beside word does ? I am familiary with for loops like for i in word and if word in key but what does if word(j) in key mean

Upvotes: 1

Views: 44

Answers (2)

Gilbert Allen
Gilbert Allen

Reputation: 343

The [j] next to word is pointing at the element at the "j"th position in word (which is presumably iterable). So if word was "hello" and j was 1, word[j] would be "e" (since numbering starts from 0).

Upvotes: 0

Mangu Singh Rajpurohit
Mangu Singh Rajpurohit

Reputation: 11420

Rewriting in simpler form :

for chr in word:
    if chr in key:
        newString = newString + key[chr]

I think It'll help you to understand stuff very well.

Upvotes: 2

Related Questions