Capitalise every other letter in a string in Python? [closed]

I've been trying to define a function that will capitalise every other letter and also take spaces into accout for example:

print function_name("Hello world") should print "HeLlO wOrLd" rather than "HeLlO WoRlD"

I hope this makes sense. Any help is appreciated.

Thanks, Oli


Solution 1:

def foo(s):
    ret = ""
    i = True  # capitalize
    for char in s:
        if i:
            ret += char.upper()
        else:
            ret += char.lower()
        if char != ' ':
            i = not i
    return ret

>>> print foo("hello world")
HeLlO wOrLd'

Solution 2:

I think this is one of those cases where a regular for-loop is the best idea:

>>> def f(s):
...     r = ''
...     b = True
...     for c in s:
...         r += c.upper() if b else c.lower()
...         if c.isalpha():
...             b = not b
...     return r
...
>>> f('Hello world')
'HeLlO wOrLd'

Solution 3:

Here is a version that uses regular expressions:

import re

def alternate_case(s):
    cap = [False]
    def repl(m):
        cap[0] = not cap[0]
        return m.group(0).upper() if cap[0] else m.group(0).lower()
    return re.sub(r'[A-Za-z]', repl, s)

Example:

>>> alternate_case('Hello world')
'HeLlO wOrLd'