小能豆

Python Why .upper change type of string

py

I have a problem with my hangman project. When matching user input (lower case) with the word to guess (upper case), I’m using .upper which is causing an error.

if user_input.upper in self.word_to_guess:
                indexes = self.find_indexes(user_input)
                self.update_progress(user_input, indexes)

                # If there is no letter to find in the word

                if self.game_progress.count('_') == 0:
                    print('\n¡Yay! You win!')
                    print('The word is: {0}'.format(self.word_to_guess))
                    quit()

and I test that .upper change to

M = 'me'
print(M)
print(type(M))
print('')

M =(M.upper)
print(str(M))
print(type(M))
print('')

result

me
<class 'str'>

<built-in method upper of str object at 0x00007FFA191B1200>
<class 'builtin_function_or_method'>

I can convert those words to lowercase. However, I need to know how to use .upper() to change only ‘me’ to ‘ME’, without changing it into a class.’builtin_function_or_method’


阅读 69

收藏
2023-12-16

共1个答案

小能豆

It looks like you are mistakenly assigning the upper method to the variable M instead of calling the method on the string. The correct way to use the upper() method is to add parentheses to call it. Here’s the corrected code:

M = 'me'
print(M)
print(type(M))
print('')

# Correct usage of upper() method
M = M.upper()
print(str(M))
print(type(M))
print('')

This will output:

me
<class 'str'>

ME
<class 'str'>

Now, M.upper() is correctly applied to the string ‘me’, and it changes the string to uppercase without converting it into a class or method. You can use the same approach in your hangman project:

if user_input.upper() in self.word_to_guess:
    indexes = self.find_indexes(user_input)
    self.update_progress(user_input, indexes)

    # If there is no letter to find in the word
    if self.game_progress.count('_') == 0:
        print('\n¡Yay! You win!')
        print('The word is: {0}'.format(self.word_to_guess))
        quit()

Make sure to use user_input.upper() with parentheses to call the upper() method on the string.

2023-12-16