py_string_sculptor — Alternating Case Across Letters
Difficulty: medium
Transform a string by alternating the case of alphabetic characters only. Non-alphabetic characters remain unchanged and are ignored for the alternation. The first alphabetic character is lowercase, the second uppercase, the third lowercase, and so on.
def string_sculptor(text: str) -> str:
Examples
>>> string_sculptor("hello")
"hElLo"
>>> string_sculptor("Hello World")
"hElLo wOrLd"
>>> string_sculptor("aBc123def")
"aBc123DeF"
>>> string_sculptor("Python3.9!")
"pYtHoN3.9!"
>>> string_sculptor("")
""
Solution
Download py_string_sculptor.pydef string_sculptor(text: str) -> str:
result = []
idx = 0
for c in text:
if c.isalpha():
result.append(c.lower() if idx % 2 == 0 else c.upper())
idx += 1
else:
result.append(c)
return "".join(result)
How It Works
Goal: Lowercase the 1st letter, uppercase the 2nd, lowercase the 3rd, etc. — counting only letters, leaving everything else alone.
Approach: Maintain a separate index idx that advances only on alphabetic characters, so non-letters never throw off the alternation rhythm.
Step by step:
- Iterate over each character of the input.
- If it's alphabetic, lowercase it when
idxis even and uppercase it when odd. Incrementidx. - Otherwise, append the character unchanged.
- Join the list back into a string.
Key concept: Decoupling the input index from a "logical" index — when you only count certain elements, keep a separate counter that ignores the rest.