I can reverse a string using the [::- 1] syntax. Take note of the example below:
text_in = 'I am 25 years old'
rev_text = text_in[::-1]
print rev_text
Output:
dlo sraey 52 ma I
How can I reverse only the letters while keeping the numbers in order?
The desired result for the example is 'dlo sraey 25 ma I'.
Here's an approach with re:
>>> import re
>>> text_in = 'I am 25 years old'
>>> ''.join(s if s.isdigit() else s[::-1] for s in reversed(re.split('(\d+)', text_in)))
'dlo sraey 25 ma I'
>>>
>>> text_in = 'Iam25yearsold'
>>> ''.join(s if s.isdigit() else s[::-1] for s in reversed(re.split('(\d+)', text_in)))
'dlosraey25maI'
Using split() and join() along with str.isdigit() to identify numbers :
>>> s = 'I am 25 years old'
>>> s1 = s.split()
>>> ' '.join([ ele if ele.isdigit() else ele[::-1] for ele in s1[::-1] ])
=> 'dlo sraey 25 ma I'
NOTE : This only works with numbers that are space separated. For others, check out timegeb's answer using regex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With