Capitalise every other letter in a string in Python?

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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'

Method 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'

Method 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'

Method 4

This should do the trick:

def function_name(input_string):
    should_capitalize = True
    chars = []
    for single_char in input_string:
        if not single_char.isalpha():
            chars.append(single_char)
            continue

        if should_capitalize:
            chars.append(single_char.upper())
        else:
            chars.append(single_char.lower())

        should_capitalize = not should_capitalize

    return ''.join(chars)

Method 5

A (hopefully elegant) recursive approach:

def funky_cap(s, use_lower=False):
    if s == '':
        return s
    elif not s[0].isalpha():
        return s[0] + funky_cap(s[1:], use_lower)
    elif use_lower:
        return s[0].lower() + funky_cap(s[1:], not use_lower)
    else: # when we need an uppercase letter
        return s[0].upper() + funky_cap(s[1:], not use_lower)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x