Python: Swap cases of a given string
Python String: Exercise-84 with Solution
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/string/python-data-type-string-exercise-84.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics