54. Reverse only the letters
Write a function reverse_letters(text) that takes a string and returns it with its letters in reverse order, while
every character that isn't a letter (spaces, digits, punctuation) stays at its position.
In other words, the positions that hold letters stay letter positions, and they are filled with the same letters,
last to first. Capitals stay capitals: H moves as H.
Example 1
text = "Hi, you!""uo, yiH!"Example 2
text = "a1b2c3""c1b2a3"Example 3
text = "12345""12345"Constraints
texthas 0 to 100 characters: English letters, digits, spaces and punctuation.
Submit also runs 9 more tests you can't see.
Practises String Methods (lesson 5).
- Strings can't be changed, so work on
chars = list(text)and"".join(chars)at the end. - Use two indexes, one at each end, moving toward each other. An index on a character that isn't a letter (
ch.isalpha()isFalse) just moves on. - When both indexes are on letters, swap them,
chars[i], chars[j] = chars[j], chars[i], and move both. Reversing the whole string,text[::-1], also moves the digits and punctuation.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def reverse_letters(text):
"""Reverse the letters, leaving everything else put.
text: str; may be empty
Returns: str, the same length, letters reversed and
every other character in its place
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.