TotalyNotUbisoft
TotalyNotUbisoft

Reputation: 63

Why do I get this error on python and how do I fix it? (loops and strings)

My code suppose to take a string to a function and then switch the caps of each char in there from h to H and E to e but I somewhat get an error in my if s why is that?

This is the error messege:

chr = str[i]

TypeError: string indices must be integers, not str

My code is:

def CapsChanger(str):

    i = str[0]
    for i in str :
        chr = str[i]

        if((ord(chr) > 46) and (ord(chr) < 91)):
            str[i].upper()

        if((ord(chr) > 96) and (ord(chr) < 126)):
            str[i].lower()
    print str       

str = raw_input()

CapsChanger(str)

input()

Upvotes: 0

Views: 103

Answers (4)

Tomasz Jakub Rup
Tomasz Jakub Rup

Reputation: 10680

i is a string, not index. If You need index use enumerate:

for idx, i in str:
    print idx, i

Insted of ord(chr) use string that represent a letter.

Insted of two if conditions use Chained Comparisons.

def CapsChanger(str):
    out = []

    for idx,chr in enumerate(str):
        if 'Z' >= chr >= 'A':
            out.append(chr.lower())

        elif 'z' >= chr >= 'a':
            out.append(chr.upper())
    print(''.join(out))

Upvotes: 0

import string

def invertCase(text):
    ## Creating a list where results will be stored
    results = list()
    ## This will contain the abc in upper and lowercase: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
    abc = string.lowercase + string.uppercase

    ## Looping each letter of the received text
    for letter in text:
        ## If the current letter of the loop exists in our abc variable contents, it means it's a letter and not a symbol or space
        ## So we can apply upper() or lower() to the letter.
        if letter in abc:
            ## If the letter is currently uppercase, then we turn it into lowercase
            if letter.isupper():
                results.append(letter.lower())
            ## If the letter is currently lowercase, then we turn it into uppercase
            else:
                results.append(letter.upper())
        ## The current letter of the loop is not in our abc variable so it could be anything but a letter
        ## So we just append it to our results list
        else:
            results.append(letter)

    ## Once the loop finishes we just join every item in the list to make the final string and return it
    return ''.join(results)

print invertCase('SoMeOnE Is hAvING fUN')

Output:

sOmEoNe iS HaVing Fun

Upvotes: 1

ergonaut
ergonaut

Reputation: 7057

The variable i is already a 1 character string because the for loop processes strings this way. Also, when you call str[i].upper(), it needs to either be assigned to something, or printed out, otherwise the character is never actually changed in place. .lower() and .upper() also have a behaviour which already checks the range for you, and returns the same characters. Eg. if it already uppercase, or a number, upper() will just return the same character.

Your function can be simplified as follows:

import sys
def CapsChanger(str):
    for i in str:
      sys.stdout.write (i.lower() if (i.upper() == i) else i.upper())
    print

str = raw_input()
CapsChanger(str)

sys.stdout.write is used to avoid printing out extra spaces. The ternary operator is used to switch case in one shot:

<value1> if <condition> else <value2>

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600026

When you do for i in str, in each iteration i represents that actual character, not the index. So you don't need to do chr = str[i] - i is already that character.

Upvotes: 3

Related Questions