Reputation:
I wrote some code to swap the cases of a string, but it seems like it's doing it quite inconsistently. I'm hoping some of you could clarify what's wrong. For the record, I'm aware of the swapcase()
method, but my initial attempt was to test how I'd approach the problem without it. Without further ado:
p = "Www.HackerRank.com → wWW.hACKERrANK.COM"
p1 = p.split(" ")
n = []
for i in p1:
item = list(p1[p1.index(i)])
for i in item:
if i.isalpha()==True:
if i.isupper()==True:
item[item.index(i)] = i.lower()
elif i.islower()==True:
item[item.index(i)] = i.upper()
else: pass
n.append(item)
for i in n:
n[n.index(i)] = "".join(n[n.index(i)])
n = " ".join(n)
That's the code. The initial string, p
is "Www.HackerRank.com → wWW.hACKERrANK.COM"
. The end result, n however, is "WWw.hACKErRANK.COM → wwW.HackeRrank.com"
.
So we have:
"Www.HackerRank.com → wWW.hACKERrANK.COM"
= p
"WWw.hACKErRANK.COM → wwW.HackeRrank.com"
= n
As you can see, some of the letters are properly converted whilst others aren't. Is it possible to fix the code so that I achieve what I want?
Upvotes: 1
Views: 41
Reputation: 3631
My suggestion would be to directly loop through the letters of the string instead of splitting it into words first:
positive = "Www.HackerRank.com → wWW.hACKERrANK.COM"
negative = []
for letter in positive:
if letter.isalpha():
if letter.isupper():
negative.append(letter.lower())
else:
negative.append(letter.upper())
else:
negative.append(letter)
negative = "".join(negative)
Please try to use meaningful names (this makes your life easier when revisiting your own code in a month or two).
Upvotes: 1