3

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
kernelram
  • 33
  • 4

8 Answers8

6

Here's a onliner

"".join([x.upper() if i%2 else x.lower() for i,x in enumerate(mystring)])
najeem
  • 1,841
  • 13
  • 29
  • 1
    You don’t need a list: `"".join(x.upper() if i%2 else x.lower() for i,x in enumerate(mystring))` – Mykola Zotko Jan 17 '19 at 09:47
  • 2
    @MykolaZotko, Except it's one instance where using a list is [more efficient](https://stackoverflow.com/a/37782238/9209546). – jpp Jan 17 '19 at 09:50
2

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
Daniel Trugman
  • 8,186
  • 20
  • 41
2

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)
fips
  • 4,319
  • 5
  • 26
  • 42
2

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
Employee
  • 3,109
  • 5
  • 31
  • 50
1

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
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73
1

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'
jpp
  • 159,742
  • 34
  • 281
  • 339
0

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"))
Anupam Jain
  • 109
  • 4
0
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')
  • hi @hydraspun thank you for your answer. Just posting some code is almost never a good answer. Maybe try to elaborate a bit your thinking and explain why your answer is the correct one. Also you might want to read up on [docstrings](https://www.python.org/dev/peps/pep-0257/). – Ente Oct 27 '19 at 23:00