Computer Science, asked by pulakjyotidas7519, 1 year ago

Define a function in python that takes a string and returns a matching string where every even letter is uppercase and odd letter in lowercase

Answers

Answered by QGP
2

String Manipulation - Python

We will be first taking in the user input of the string.

We need every odd letter lowercase and every even letter uppercase. Since we only want to alternate letters, we must do something if special characters, numbers or spaces are present in the string.

We can create a string containing all of these, and ignore them as we are going through the user string.

We would keep a separate letter count, which would increment only when letters are found.

Here's a program code, which does the required job.

 \rule{320}{1}

# Python Program to take a string input

# and to return a matching string where

# every even letter is uppercase and

# every odd letter is lowercase

string = input("Enter a string: ")  # Take User Input

def manipulateString(string):   # The Function

   newstring = ""  # Create an empty string

   # We will only consider letters and  

   # ignore special characters and numbers

   ignorelist = " !\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~0123456789"

   # We must keep count of letters for even and odd    

   lettercount = 1;

   # Iterate a loop over the characters in string

   for character in string:

       # If character is a special character,  

       # simply add to newstring and continue

       if(character in ignorelist):

           newstring += character

           continue

       # If character is a letter, then check even/odd condition

       if(lettercount % 2 == 0):

           newstring += character.upper()

       else:

           newstring += character.lower()

       lettercount += 1    # Increment letter count

   return newstring

# Print out the final required string by calling the function

print("The matching string is:", manipulateString(string))

Attachments:
Answered by Bebbbb
0

Answer:

def myfunc(string):

char_count = 0

sb = []
matching_string = ‘’

while char_count < len(string):

if char_count % 2 == 0:

sb.append(string[char_count].upper())

else:

sb.append(string[char_count].lower())

char_count+=1

return matching_string.join(sb)

Explanation:

Similar questions