w3resource

Python: Swap cases of a given string


Swap cases in string.

Write a Python program to swap cases in a given string.

Sample Solution:

Python Code:

# Define a function to swap the case of characters in a string
def swap_case_string(str1):
    # Initialize an empty string to store the result
    result_str = ""
    
    # Iterate through each character in the input string
    for item in str1:
        # Check if the character is uppercase
        if item.isupper():
            # If uppercase, convert to lowercase and append to the result string
            result_str += item.lower()
        else:
            # If lowercase, convert to uppercase and append to the result string
            result_str += item.upper()
    
    # Return the final swapped case string
    return result_str

# Test the function with different input strings and print the results
print(swap_case_string("Python Exercises"))
print(swap_case_string("Java"))
print(swap_case_string("NumPy"))

Sample Output:

pYTHON eXERCISES
jAVA
nUMpY

Flowchart:

Flowchart: Swap cases of a given string.

Python Code Editor:

Previous: Write a Python program to print four values decimal, octal, hexadecimal (capitalized), binary in a single line of a given integer.
Next: Write a Python program to convert a given Bytearray to Hexadecimal string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.