-2

Need support/please clear my doubt:

def test(strValue):
    for i in range(len(strValue)):
        if[ i %2==0]:
            strValue.replace(strValue[i] ,strValue[i].upper())
            print('if loop '+strValue)
        else:
            strValue.replace(strValue[i] ,strValue[i].lower())
            print('else loop '+strValue)
**input:**
 test('apple')
**output:**
if loop apple
if loop apple
if loop apple
if loop apple
if loop apple

1.why if[ i %2==0] is always true 2.why strValue is not changed

2 Answers2

0

To answer your problems

  1. The value of [i%2==0] is not always equal to True, it is either [True] or [False] depending on the i value but the non-empty list like [True] or [False] is always True so try to do this way

    i%2==0 instead of [i%2==0]

  2. You're replacing the strValue but not assigning it back. So do this way-

    strValue = strValue.replace(strValue[i] ,strValue[i].upper())

DEMO & EXPLANATION: https://rextester.com/AHJHS98230

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

1- [i%2==0] is a list of one element being the result of your test. In python, the brackets build a list. So you should just remove the bracket and your test will be fine.

2- strValue.replace(strValue[i] ,strValue[i].lower()) is not in-place modification. Strings are immutable in python so you need to store the result of this call in strValue and hence erase the former value.

So the working code in your case is:

def test(strValue):
    for i in range(len(strValue)):
        if i %2==0:
            strValue = strValue.replace(strValue[i] ,strValue[i].upper())
            print('if loop '+strValue)
        else:
            strValue = strValue.replace(strValue[i] ,strValue[i].lower())
            print('else loop '+strValue)
LucG
  • 1,238
  • 13
  • 25
  • thanks .code works but **input:** test('apple') **output:** if loop Apple else loop Apple if loop APPle else loop APPle if loop APPlE -- In 3 rd line output is "if loop APPle" i am not clear why both p changed to P – Palaniappan Somu Apr 18 '20 at 07:13