Home > front end >  Taking a string as input and convert the letters?
Taking a string as input and convert the letters?

Time:01-21

I want to take a string as input and convert the even letters to uppercase and odd letters to lowercase. Is there any other way to do it?

def myfunc(word):
    result = ''
    index = 0
    
    for letter in word:
        if index % 2 ==0:
            result  = letter.lower()
        else:
            result  =letter.upper()
        index  = 1
        

    return result

CodePudding user response:

There's many more interesting ways to skin this cat, but here's an abbreviated one:

def myfunc(word):
    action = {0: str.lower, 1: str.upper}
    return ''.join([action[index % 2](letter)
                    for index, letter in enumerate(word)])


print(myfunc('hello world'))

CodePudding user response:

Many, many different ways to do it but here's one you might like. It's a little more concise and one might argue a bit more 'Pythonic'.

def myfunc(word):

    # Convert everything to lowercase
    word = word.lower()
    # Convert to list of individual letters
    letters = list(word)
    # Convert every other character starting from the 2nd
    # to uppercase
    for i in range(1, len(word)   1, 2):
        letters[i] = letters[i].upper()
    # Convert back to string
    return ''.join(letters)

CodePudding user response:

It looks like there's a more pythonic solution provided, so I'd like to give a slightly less pythonic solution for variety.

def funnyCase(word):
    i = 0
    # convert everything to lowercase
    word = word.lower()
    # convert to a list of characters
    letters = list(word)
    # make it funny
    for letter in letters:
        # This is bitwise XOR. It's a different way to check even/odd.
        if i^1==0:
            letters[i] = letter.upper()
        i  
    return ''.join(letters)

I do hope you understand John Gordon's comment about multiple solutions. This is the beauty of programming - there is no one way to do things.

Edit - I messed up. Happens

  •  Tags:  
  • Related