Home > front end >  for loop , trying to print all element with index
for loop , trying to print all element with index

Time:07-06

why following code is giving the error
TypeError                                 Traceback (most recent call last)
<ipython-input-14-31d3f85500ea> in <module>
      1 name = "Shyam"
      2 for x in name:
----> 3     print(x,"th position elements are : ", name[x])

TypeError: string indices must be integers

code :

name = "Shyam"
for x in name:
    print(x,"th position elements are : ", name[x])

CodePudding user response:

x is a character from name, you can't use it as index. To get the caracters and their index simultaneously use enumerate

name = "Shyam"
for i, x in enumerate(name):
    print(i, "th position elements are : ", x)

This will print

0 th position elements are :  S
1 th position elements are :  h
2 th position elements are :  y
3 th position elements are :  a
4 th position elements are :  m

CodePudding user response:

x is a character from the string name

So, in the first iteration of your loop you can assert that x == 'S'

This leads (effectively) to this expression:

name['S']

Given that name is a string, this will induce the error you're seeing

CodePudding user response:

x will not be an integer the way you have defined it, and that is why you are getting an error because as the error explicitly says string indices must be integers.

The code should be corrected as below:

name = "Shyam"
for x in range(len(name)):
    print(x,"th position elements are : ", name[x])

and the output will be:

0 th position elements are :  S
1 th position elements are :  h
2 th position elements are :  y
3 th position elements are :  a
4 th position elements are :  m

CodePudding user response:

The code below will work. the variable name is not a number. In a for loop it needs a number to iterate through.

name = "Shyam"
for x in range(len(name)):
    print(x, "The Character at %d Position = %c" %(x, name[x]))
  • Related