Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a string in Python but keep numbers in original order

Tags:

python

string

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

like image 818
Idreams Avatar asked Apr 24 '26 05:04

Idreams


2 Answers

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'
like image 128
timgeb Avatar answered Apr 26 '26 18:04

timgeb


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.

like image 38
Kaushik NP Avatar answered Apr 26 '26 19:04

Kaushik NP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!