Search code examples
pythonargv

TypeError while looping through argv (Python)


Trying to iterate through command line argument to check if each of the chars inside the string is an alphabet.

TypeError: string indices must be integers

import sys

k = sys.argv[1]

if len(sys.argv) != 2:
    print("Error.")
    return 1
else:
    for i in k:
        if k[i].isalpha() == False:
            return 1
            print("Error.")

Solution

  • Change the if statement inside the else statement to if i.isalpha() == False:

    This is because the for loop iterates through the values of k and sets the variable i equal to the k[i]

    If you would like to have the for loop set I to the indexes instead, the for loop must read as such:

    for i in range(len(k)):