Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "AttributeError: 'str' object has no attribute 'uppercase'" occurs
when we try to call the uppercase()
method on a string. To solve the error,
use the upper()
method to uppercase a string, e.g. 'abc'.upper()
.
Here is an example of how the error occurs.
my_str = 'hello world' # ⛔️ AttributeError: 'str' object has no attribute 'uppercase' result = my_str.uppercase()
Strings don't have an uppercase()
method in Python, however you can use the
upper()
method to uppercase a string.
my_str = 'hello world' result = my_str.upper() print(result) # 👉️ "HELLO WORLD"
The str.upper method returns a copy of the string with all the cased characters converted to uppercase.
Make sure to store the result in a variable as the original string remains unchanged.
Conversely, you can use the lower()
method to convert a string to lowercase.
my_str = 'HELLO WORLD' result = my_str.lower() print(result) # 👉️ "hello world"
The str.lower method returns a copy of the string with all the cased characters converted to lowercase.
You can use the str.title()
method to get the titlecased version of a string.
my_str = 'james doe' result = my_str.title() print(result) # 👉️ "James Doe"
The str.title method returns a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.
Note that the algorithm also converts characters after apostrophes to uppercase.
my_str = "it's him" result = my_str.title() print(result) # 👉️ "It'S Him"
The string.capwords method doesn't have this problem, as it only splits words on spaces.
from string import capwords my_str = "it's him" result = capwords(my_str) print(result) # 👉️ "It's Him"
A good way to start debugging is to print(dir(your_object))
and see what
attributes a string has.
Here is an example of what printing the attributes of a string
looks like.
my_string = 'hello world' # [ 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', # 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', # 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', # 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', # 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', # 'title', 'translate', 'upper', 'zfill'] print(dir(my_string))
If you pass a class to the dir() function, it returns a list of names of the classes' attributes, and recursively of the attributes of its bases.
Since the str
object doesn't implement a uppercase()
method, the error is
caused.