Reverse a string if its length is a multiple of 4

EasyString Programs · 4 of 106

Write a Python program to reverse a string if its length is a multiple of 4; otherwise return it unchanged.

Advertisement
Input
"Python", "sqatools"
Output
Python -> Python
sqatools -> slootaqs

Approach

  1. Check len(text) % 4 == 0, then reverse with [::-1].

Solution

Python
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.

More string programs

← All 106 String Programs

Leave a Comment