3

I have a string, I need to reverse just the numbers in the string without the text:

String: [321 test]

The result will be: [123 test]

closed as off-topic by user30184, radouxju, Vince, Erica, nmpeterson Sep 17 '14 at 16:30

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions about software development are off-topic here unless they relate directly to Geographical Information Systems, but they can be asked on Stack Overflow." – user30184, radouxju, Vince, Erica, nmpeterson
If this question can be reworded to fit the rules in the help center, please edit the question.

12

Something like this should work:

def reverse(s):
    items = s.split()
    digs = ''.join(i for i in s if i.isdigit())
    dr = digs[::-1]
    return ' '.join(map(None, items)).replace(digs, dr)

>>> reverse('321 test')
'123 test'

@mnpeterson brought up a good point about assuming where the numbers are...My post above would string all digits together even if they were separated so below is an edited version that would work better:

def reverse(s):
    items = str(s).split()
    dr = []
    for it in items:
        d = ''.join(i for i in it if i.isdigit())
        if d != '':
            dr.append(d[::-1])
        else:
            dr.append(it)
    return ' '.join(dr)

tests = ['321 test', 'test test 7868', '1234 test 7890 test', 'test test 1',
         'test test test', '123 321 456 test 98089897 test']
for t in tests:
    print reverse(t)

this printed:

123 test
test test 8687
4321 test 0987 test
test test 1
test test test
321 123 654 test 79898089 test
  • I like this answer better than @artwork21's because it doesn't assume there is only one number and that it must come first. However, both answers assume the numbers are separated from other text by spaces, which may or may not meet the OP's needs. – nmpeterson Sep 17 '14 at 16:35
  • 1
    Thanks @mnpeterson...I decided to add an edited version that will ensure that the groups of numbers would be split properly. The way I had it before, all the numbers would have been strung together into one even they were separated in the original text. Props to artwork21 as well. – crmackey Sep 17 '14 at 16:53
4

This function should work in field calculator (if your text is always after the numbers with a empty space):

def rev(x): 
  try:
    nonValue = x.split(' ')[1]
    value = ''.join(i for i in x if i.isdigit())[::-1]
    return value + ' ' + nonValue
  except ValueError:
    pass

Output e.g.:

enter image description here

  • wow, we posted almost the exact same answer! – crmackey Sep 17 '14 at 14:38
  • This function work just for numbers and delete the Text – mahmoud hageer Sep 18 '14 at 6:16
  • @mahmoud hageer, See output e.g. in my answer, how is your text getting deleted? – artwork21 Sep 18 '14 at 12:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.