I would like to change the chars of a string from lowercase to uppercase.
My code is below, the output I get with my code is a
; could you please tell me where I am wrong and explain why?
Thanks in advance
test = "AltERNating"
def to_alternating_case(string):
words = list(string)
for word in words:
if word.isupper() == True:
return word.lower()
else:
return word.upper()
print to_alternating_case(test)
If you want to invert the case of that string, try this:
Here is a short form of the hard way:
As I was looking for a solution making a all upper or all lower string alternating case, here is a solution to this problem:
You are returning the first alphabet after looping over the word alternating which is not what you are expecting. There are some suggestions to directly loop over the string rather than converting it to a list, and expression
if <variable-name> == True
can be directly simplified toif <variable-name>
. Answer with modifications as follows:OR using list comprehension :
OR using map, lambda:
Your loop iterates over the characters in the input string. It then returns from the very first iteration. Thus, you always get a 1-char return value.
That's because your function returns the first character only. I mean
return
keyword breaks yourfor
loop.Also, note that is unnecessary to convert the string into a list by running
words = list(string)
because you can iterate over a string just as you did with the list.If you're looking for an algorithmic solution instead of the
swapcase()
then modify your method this way instead: