I am trying to take a string, check every single character in the string, and swap the case for the opposite. For example, 'Seoul'
would become 'sEOUL'
. (I realize that Python's builtin str.swapcase
method exists, but am trying to reimplement it as a learning exercise.)
This is my code.
str = "My name is Shah, and I recently went to Mission Nightclub"
str_arr = [str.upper[0] + str.upper[1:] if str[index].islower() else str[index].lower for (index, val) in enumerate(str.split)]
print(str_arr)
The idea is that I use enumerate
and a list comprehension. First, it takes the whole string and splits it into a list where each element is a word. Then, it'll use enumerate
to get the index of each element in the list. Then I have two conditions: one checks if the i
th character is lowercase, and if it is, it'll convert it to uppercase; else it'll convert to lowercase. Then, for each i
th element in the new list created, it'll take the first element and uppercase it and the rest of the element using string slicing to get the rest of the characters in the word.
However, I get this error:
Traceback (most recent call last):
File "/Users/shah/test.py", line 2, in <module>
str_arr = [str.upper[0] + str.upper[1:]if str[index].islower() else str[index].lower for (index, val) in enumerate(str.split)]
TypeError: 'builtin_function_or_method' object is not iterable
Why doesn't my code work, and how do I fix it?