You could sort the unique characters in the input string and apply indices to each letter by using the enumerate()
function:
def stringConvert(s):
ordinals = {c: str(ordinal) for ordinal, c in enumerate(sorted(set(s)), 1)}
return ''.join([ordinals[c] for c in s])
The second argument to enumerate()
is the integer at which to start counting; since your ordinals start at 1 you use that as the starting value rather than 0
. set()
gives us the unique values only.
ordinals
then is a dictionary mapping character to an integer, in alphabetical order.
Demo:
>>> def stringConvert(s):
... ordinals = {c: str(ordinal) for ordinal, c in enumerate(sorted(set(s)), 1)}
... return ''.join([ordinals[c] for c in s])
...
>>> stringConvert('DABC')
'4123'
>>> stringConvert('XPFT')
'4213'
Breaking that all down a little:
>>> s = 'XPFT'
>>> set(s) # unique characters
set(['X', 'F', 'T', 'P'])
>>> sorted(set(s)) # unique characters in sorted order
['F', 'P', 'T', 'X']
>>> list(enumerate(sorted(set(s)), 1)) # unique characters in sorted order with index
[(1, 'F'), (2, 'P'), (3, 'T'), (4, 'X')]
>>> {c: str(ordinal) for ordinal, c in enumerate(sorted(s), 1)} # character to number
{'P': '2', 'T': '3', 'X': '4', 'F': '1'}