# Convert String to List of Numbers

I want to create a function that when a string is entered it will turn it into a list of numbers, these numbers are the numerical form of the characters in the string.

e.g. a=1, b=2, c=3, d=4 and space = 27 (other punctuation may be needed).

So if I had the string "hello", my result would be: {8, 5, 12, 12, 15}

I had a look at StringReplace, StringSplit and Characters, but not sure what is optimal.

How would I go about doing this?

You can start by using ToCharacterCode then applying whatever rules you want using ReplaceAll.

For example, to get "a" aligned to one we will need to subtract 96 from the ASCII value:

string = "hello world";
rules = {-64 -> 27};
ToCharacterCode[string] - 96
% /. rules

{8, 5, 12, 12, 15, -64, 23, 15, 18, 12, 4}

{8, 5, 12, 12, 15, 27, 23, 15, 18, 12, 4}


Less efficiently but also perhaps easier to work with for mapping a few characters atypically (such as space above) you can do this:

Characters @ string /.
{" " -> 27, x_String :> ToCharacterCode[x] - 96} // Flatten


{8, 5, 12, 12, 15, 27, 23, 15, 18, 12, 4}

The rules have priority by order therefore ToCharacterCode is only used on the characters you haven't already replaced.

It may help to have a sense of the ASCII mapping:

FromCharacterCode[Range[32, 126]]

" !\"#\$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnopqrstuvwxyz{|}~"
`
• Wow, so many hidden features in Mathematica, This is brilliant – VikeStep Aug 15 '13 at 11:42
• @user9053 Yes, even people who have been using it for years continue to find new things. – Mr.Wizard Aug 15 '13 at 12:07