kernelram
kernelram

Reputation: 33

How to change uppercase & lowercase alternatively in a string?

I want to create a new string from a given string with alternate uppercase and lowercase.

I have tried iterating over the string and changing first to uppercase into a new string and then to lower case into another new string again.

def myfunc(x):
    even = x.upper()
    lst = list(even)
    for itemno in lst:
        if (itemno % 2) !=0:
            even1=lst[1::2].lowercase()
        itemno=itemno+1   
    even2=str(even1)
    print(even2)

Since I cant change the given string I need a good way of creating a new string alternate caps.

Upvotes: 3

Views: 1489

Answers (8)

hydraspun
hydraspun

Reputation: 1

def myfunc(string):
    # Un-hash print statements to watch python build out the string.
    # Script is an elementary example of using an enumerate function.
    # An enumerate function tracks an index integer and its associated value as it moves along the string.
    # In this example we use arithmetic to determine odd and even index counts, then modify the associated variable.
    # After modifying the upper/lower case of the character, it starts adding the string back together.
    # The end of the function then returns back with the new modified string.
    #print(string)
    retval = ''
    for space, letter in enumerate(string):
        if space %2==0:
            retval = retval + letter.upper()
            #print(retval)
        else:
            retval = retval + letter.lower()
            #print(retval)
    print(retval)
    return retval
myfunc('Thisisanamazingscript')

Upvotes: 0

Mykola Zotko
Mykola Zotko

Reputation: 17794

Using a string slicing:

from itertools import zip_longest

s = 'example'

new_s = ''.join(x.upper() + y.lower()
                for x, y in zip_longest(s[::2], s[1::2], fillvalue=''))
# ExAmPlE

Using an iterator:

s_iter = iter(s)

new_s = ''.join(x.upper() + y.lower()
                for x, y in zip_longest(s_iter, s_iter, fillvalue=''))
# ExAmPlE

Using the function reduce():

def func(x, y):
    if x[-1].islower():
        return x + y.upper()
    else:
        return x + y.lower()

new_s = reduce(func, s) # eXaMpLe

Upvotes: 1

Anupam Jain
Anupam Jain

Reputation: 109

This code also returns alternative caps string:-

def alternative_strings(strings):
        for i,x in enumerate(strings):
            if i % 2 == 0:
                print(x.upper(), end="")
            else:
                print(x.lower(), end= "")
        return ''


print(alternative_strings("Testing String"))

Upvotes: 0

jpp
jpp

Reputation: 164613

Here's a solution using itertools which utilizes string slicing:

from itertools import chain, zip_longest

x = 'inputstring'

zipper = zip_longest(x[::2].lower(), x[1::2].upper(), fillvalue='')
res = ''.join(chain.from_iterable(zipper))

# 'iNpUtStRiNg'

Upvotes: 1

Employee
Employee

Reputation: 3233

This does the job also

def foo(input_message):

    c = 0 
    output_message = ""

    for m in input_message:
        if (c%2==0):
            output_message = output_message + m.lower() 
        else: 
            output_message = output_message + m.upper()
        c = c + 1 

    return output_message

Upvotes: 2

najeem
najeem

Reputation: 1921

Here's a onliner

"".join([x.upper() if i%2 else x.lower() for i,x in enumerate(mystring)])

Upvotes: 6

fips
fips

Reputation: 4379

Here's one that returns a new string using with alternate caps:

def myfunc(x):
   seq = []
   for i, v in enumerate(x):
      seq.append(v.upper() if i % 2 == 0 else v.lower())
   return ''.join(seq)

Upvotes: 2

Daniel Trugman
Daniel Trugman

Reputation: 8491

You can simply randomly choose for each letter in the old string if you should lowercase or uppercase it, like this:

import random

def myfunc2(old):
  new = ''
  for c in old:
    lower = random.randint(0, 1)
    if lower:
      new += c.lower()
    else:
      new += c.upper()
  return new

Upvotes: 2

Related Questions