Home > Software design >  Function to find capital letters in a word
Function to find capital letters in a word

Time:12-29

There is function to find capital letters in a word and and returns the index of that letter in the list.

def capslock(word):
    res = []
    for i,j in enumerate(word):
        if j.isupper():
            res.append(i)
    return  res
print(capslock("JDhfjkShh"))

[0,1,6]


I don’t understand why if you swap the loop variables in places (like that)

def capslock(word):
    res = []
    for j,i in enumerate(word):
        if j.isupper():
            res.append(i)
    return  res
print(capslock("JDhfjkShh"))

it gives me  AttributeError: 'int' object has no attribute 'isupper'



I believe that the problem is that when the first variable is checked for the if condition in the loop and if the condition is met (the letter in the argument word is large), then the next variable remains empty and has nothing to return to result list . is my guess correct that first both variables should fall under the in enumerate function so that one variable checks the letter and the other puts it in the list - the result

I guess this is not a dumb question for a 6 day study.

updated:thanks for the feedback, you made it clear that this is still a stupid question, I will try not to distract you with this anymore

CodePudding user response:

try this code:

caps="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def capslock(word):
    res = []
    for letter in range(len(word)):
        if word[letter] in caps:
            res.append(word[letter])
    return res

the code bellow will will check each letter and see if its inside caps if it is it will be added to res. You can modify this code to get the index of the letter using letter

Example:

caps="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def capslock(word):
    res = []
    for letter in range(len(word)):
        if word[letter] in caps:
            res.append(letter)
    return res

this code will return the index instead of the letter itself.

CodePudding user response:

In the 2nd code you have swiped the name of the variables in the 4th and 5th line of the code

if i.isupper():
        res.append(j)

The code should be:

def capslock(word):
    res = []
    for j,i in enumerate(word):
        if i.isupper():
            res.append(j)
    return  res
print(capslock("JDhfjkShh"))

This will print [0, 1, 6]

since j is a int and i is a 'str'. You are getting this error

CodePudding user response:

following @Shounak Das code id like to improve it using comprehension list because it will be much faster than using a regular for

def capslock(word):
    return [index for index, letter in enumerate(word) if letter.isupper()]

print(capslock("ThisIsATittle"))

this will print [0, 4, 6, 7]

hope this was useful

  • Related