Reverse a string in Python but keep numbers in original order

Viewed 1850

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

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

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.

Here is a step by step approach:

text_in = 'I am 25 years old'
text_seq = list(text_in)                          # make a list of characters
text_nums = [c for c in text_seq if c.isdigit()]  # extract the numbers

num_ndx = 0
revers = []
for idx, c in enumerate(text_seq[::-1]):          # for each char in the reversed text
    if c.isdigit():                               # if it is a number
        c = text_nums[num_ndx]                    # replace it by the number not reversed
        num_ndx += 1
    revers.append(c)                              # if not a number, preserve the reversed order
print(''.join(revers))                            # output the final string              

Output :

dlo sraey 25 ma I

You can do it in pythonic way straight forward like below..

def rev_except_digit(text_in):
    rlist = text_in[::-1].split() #Reverse the whole string and split into list

    for i in range(len(rlist)): # Again reverse only numbers
        if rlist[i].isdigit():
            rlist[i] = rlist[i][::-1]
    return ' '.join(rlist)

Test:

Original: I am 25 years 345 old 290
Reverse: 290 dlo 345 sraey 25 ma I

you can find official python doc here split() and other string methods, slicing[::-1]

text = "I am 25 years old"
new_text = ''
text_rev = text[::-1]
for i in text_rev.split():
    if not i.isdigit():
         new_text += i + " ";
    else:
        new_text += i[::-1] + " ";


print(new_text)
Related