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]
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.
Sign up to join this communitySomething 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
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.: