Oscar Johansson Oscar Johansson - 7 months ago 17
Python Question

'type' object is not subscriptable in PYTHON while trying to print list

I want my program to output strings not instantly. I want it to type one character every 0.2 seconds. I wrote this code and it's giving me 'type' object is not subscriptable. Any ideas?

import sys
import time

botString = " "
#splits sentences into words
botStringSplit = botString.split()
#splits words into characters
listOfBotStringChar = list[botStringSplit]


def botType(botString):
for i in range(len(botStringSplit)):
time.sleep(0.2)
print(listOfBotStringChar[i])


userInput = input("type something")

if "hi" in userInput:
botString = "Hello friend"
botType(botString)


UPDATE:
zondo and Jacques Gaudin suggested that I should change

listOfBotStringChar = list[botStringSplit]


to

listOfBotStringChar = list(botStringSplit)


this removes the error (thanks) but it doesn't output anything. Do you guys know why?

Answer

Your problem is here:

botStringSplit = botString.split()
#splits words into characters
listOfBotStringChar = list[botStringSplit]

.split() already returns a list. So your code is having issues when you are trying to index into the list type here: list[botStringSplit].

If you wanted to convert to a list, use parenthesis instead: list(some_iterable) - but as mentioned above, this should not be necessary as it would be equivalent to: botStringSplit = list(botString.split())

This will do what you want (in python 3), if you are in python 2, switch the input() to raw_input()

import time

def botType(botString):
    for i in range(len(botString)):
        time.sleep(0.2)
        print(botString[i])

userInput = input("type something: ")
if "hi" in userInput:
    botString = "Hello friend"
    botType(botString)