Home > Net >  I converted a string into a list when I used another variable to access a list I am getting a type e
I converted a string into a list when I used another variable to access a list I am getting a type e

Time:10-12

print("<<== program to select and display words of an user input string ==>>")
s=str(input("enter a string:   "))
split1=s.split()
len1=len(split1)
header1="----------------------------------------------"
heading="printing words and ther indexes"
print(header1)
print(heading.center(45))
print(header1)
for x in range(0,len1):
     print("        ",x,"---->",split1[x])
print(header1)
print('')
print('')
g=input('enter the index of the word to display:  ')
print(split1[g])

I am getting:

line 16, in <module>
    print(split1[g])
TypeError: list indices must be integers or slices, not str

CodePudding user response:

input() returns string by default. You have to use int() to convert it to an integer because index can't be a string. So, it needs to be like this:

g = int(input('enter the index of the word to display:  '))
print(split1[g])

Edit: I got it what you're trying to do using variable g For that, you have to use index() like this

g = input('enter the index of the word to display:  ')
print(split1.index(g))
  • Related