Home > Mobile >  The Whole String isn't getting capitalized
The Whole String isn't getting capitalized

Time:10-12

I have to create a code to capitalize the even part of string.split() and decapitalize the odd. However the code only returns the first part of the string as the result. I have some problems whith result().. I know about that but can somebody pinpoint the exact place?
The Code-

 def somefunc(some_string):
        x=some_string.split()
        for something in x:
            if x.index(something)%2==0:
                return something.upper()
            elif x.index(something)!=0:
                return something.lower()
        y=" ".join(x)

The Result-

myfunc("hey dude")
'HEY'

CodePudding user response:

The main issue is that you are returning early, do this instead:

def some_func(some_string):
    x = some_string.split()
    result = []
    for i, something in enumerate(x):
        if i % 2 == 0:
            result.append(something.upper())
        else:
            result.append(something.lower())
    return " ".join(result)


print(some_func("hey dude"))

Output

HEY dude

Note that using index won't work, think in the case when you have duplicated words (for example "hey hey dude"). The solution is to use enumerate to keep track of the index. As an alternative you can use a list comprehension:

def some_func(some_string):
    x = some_string.split()
    return " ".join([something.upper() if i % 2 == 0 else something.lower() for i, something in enumerate(x)])

Note

You could also take advantage of the fact that in Python functions are first-class citizens and do:

def some_func(some_string):
    x = some_string.split()
    cases = [str.upper, str.lower]
    return " ".join([cases[i % 2](something) for i, something in enumerate(x)])

CodePudding user response:

def some_method(txt):
    return ' '.join(map(lambda x: x[1].lower() if x[0] % 2 else x[1].upper(), enumerate(txt.split(' '))))


some_method('Hello Dude')


>>> 'HELLO dudde'

CodePudding user response:

As others have pointed out, functions only return one value and terminate. What about if you want to have many returns? It's possible with Python generators! You have already written your function in a generator-ish style.

Here's a slightly modified generator that will go through a string, split it and yield upper case versions of even-numbered words:

def uppercase_odd(s):
    for k, w in enumerate(s.split()):
        yield w.lower() if k % 2 else w.upper()

It returns (yields) lower and uppercase words alternatively. Here's how you would use it:

' '.join(uppercase_odd('Hey My Dude'))

Result:

'HEY my DUDE'
  • Related