Python Practice › String Programs › Program 4
Reverse a string if its length is a multiple of 4
Write a Python program to reverse a string if its length is a multiple of 4; otherwise return it unchanged.
Input
"Python", "sqatools"
Output
Python -> Python sqatools -> slootaqs
Approach
- Check
len(text) % 4 == 0, then reverse with[::-1].
Solution
for text in ["Python", "sqatools"]: result = text[::-1] if len(text) % 4 == 0 else text print(text, "->", result)Output
Python -> Python sqatools -> slootaqs
Line by line
Line 2
“sqatools” has 8 characters, so it is reversed; “Python” has 6, so it is not.
Learn the concept
New to this topic? Read the lesson, then come back.