5

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)
cs95
  • 379,657
  • 97
  • 704
  • 746
  • The reason why your code doesn't work is that "return" will leave the current function ('to_alternating_case()'). If you want to implement .swapcase() for educational purposes – mutate the "words"-list instead of returning at first character. – folkol Mar 27 '16 at 14:08

12 Answers12

16

If you want to invert the case of that string, try this:

>>> 'AltERNating'.swapcase()
'aLTernATING'
Adriano
  • 3,788
  • 5
  • 32
  • 53
folkol
  • 4,752
  • 22
  • 25
3

There are two answers to this: an easy one and a hard one.

The easy one

Python has a built in function to do that, i dont exactly remember what it is, but something along the lines of

string.swapcase()

The hard one

You define your own function. The way you made your function is wrong, because iterating over a string will return it letter by letter, and you just return the first letter instead of continuing the iteration.

def to_alternating_case(string):
    temp = ""
    for character in string:
        if character.isupper() == True:
            temp += character.lower()
        else:
            temp += word.upper()
    return temp
Amit Gold
  • 727
  • 7
  • 22
  • Concatenating strings in a loop can be slow. Consider adding them in a list first and then joining them with `''.join(list_of_chars)` in the end. – Georgy Aug 21 '20 at 20:52
1

That's because your function returns the first character only. I mean return keyword breaks your for 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:

test = "AltERNating"

def to_alternating_case(string):
    res = ""
    for word in string:
        if word.isupper() == True:
            res = res + word.lower()
        else:
            res = res + word.upper()
    return res


print to_alternating_case(test)
Community
  • 1
  • 1
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
1

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.

test = "AltERNating"

def to_alternating_case(string):
    words = list(string)
    rval = ''
    for c in words:
        if word.isupper():
            rval += c.lower()
        else:
            rval += c.upper()
    return rval    

print to_alternating_case(test)
user2390182
  • 72,016
  • 6
  • 67
  • 89
1

You should do that like this:

test = "AltERNating"

def to_alternating_case(string):
    words = list(string)
    newstring = ""
        if word.isupper():
            newstring += word.lower()
        else:
            newstring += word.upper()  
    return alternative
print to_alternating_case(test)
Lev Leontev
  • 2,538
  • 2
  • 19
  • 31
1

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 to if <variable-name>. Answer with modifications as follows:

test = "AltERNating"

def to_alternating_case(string):
    result = ''
    for word in string:
        if word.isupper():
            result += word.lower()
        else:
            result += word.upper()
    return result

print to_alternating_case(test)

OR using list comprehension :

def to_alternating_case(string):
    result =[word.lower() if word.isupper() else word.upper() for word in string]
    return ''.join(result)

OR using map, lambda:

def to_alternating_case(string):
    result = map(lambda word:word.lower() if word.isupper() else word.upper(), string)
    return ''.join(result)
pppery
  • 3,731
  • 22
  • 33
  • 46
hemraj
  • 964
  • 6
  • 14
1
def myfunc(string):
    i=0
    newstring=''
    for x in string:
        if i%2==0: 
            newstring=newstring+x.lower()
        else:
            newstring=newstring+x.upper()
        i+=1
    return newstring
jadelord
  • 1,511
  • 14
  • 19
0
contents='abcdefgasdfadfasdf'
temp=''
ss=list(contents)
for item in range(len(ss)):
    if item%2==0:
        temp+=ss[item].lower()
    else:
        temp+=ss[item].upper()

print(temp)

you can add this code inside a function also and in place of print use the return key

0
string=input("enter string:")
temp=''
ss=list(string)
for item in range(len(ss)):
    if item%2==0:
        temp+=ss[item].lower()
    else:
        temp+=ss[item].upper()
print(temp)
0

Here is a short form of the hard way:

alt_case = lambda s : ''.join([c.upper() if c.islower() else c.lower() for c in s])
print(alt_case('AltERNating'))

As I was looking for a solution making a all upper or all lower string alternating case, here is a solution to this problem:

alt_case = lambda s : ''.join([c.upper() if i%2 == 0 else c.lower() for i, c in enumerate(s)])
print(alt_case('alternating'))
Phidelux
  • 2,043
  • 1
  • 32
  • 50
0

You could use swapcase() method

string_name.swapcase()

or you could be a little bit fancy and use list comprehension

string = "thE big BROWN FoX JuMPeD oVEr thE LAZY Dog"
y =  "".join([val.upper() if val.islower() else val.lower() for val in string])
print(y)

>>> 'THe BIG brown fOx jUmpEd OveR THe lazy dOG'
Nikhilbv
  • 73
  • 2
  • 10
0

This doesn't use any 'pythonic' methods and gives the answer in a basic logical format using ASCII :

sentence = 'aWESOME is cODING'

words = sentence.split(' ') 
sentence = ' '.join(reversed(words)) 

ans =''
for s in sentence:
    if ord(s) >= 97 and ord(s) <= 122:
        ans = ans + chr(ord(s) - 32)
    elif ord(s) >= 65 and ord(s) <= 90 :
        ans = ans + chr(ord(s) + 32)
    else :
        ans += ' '
print(ans)

So, the output will be : Coding IS Awesome

Suvoo
  • 1
  • 1