# How can I associate letters with numbers in a text, keeping their positions?

I would like to ask you how I can associate a letter with a number in Mathematica. I have a text/string, let's say sentence="hello world!", and I would like to substitute each character with a number. So what I am looking for is something like this:

h-> 1
e-> 2
l -> 3
l-> 4
o -> 5
(space) -> 6
w-> 7
and so on
!-> 12


Of course, the text that I am considering contains more than 12 characters, so I cannot do it manually. Could you help me to understand which function I should consider/create to do that?

Many thanks

• does ToCharacterCode[sentence] give what you need? or AssociationThread[Characters[sentence],ToCharacterCode[sentence]] ?
– kglr
Commented Sep 20, 2019 at 18:10
• Are you looking for something like string = "hello world!"; Range[StringLength[string]] which outputs the numbers 1 through 12 in a list? If you're looking for actual replacement rules, how should the code determine what numbers should be associated with repeated characters (like the "ll" in "hello")? Commented Sep 20, 2019 at 18:12
• Rule @@@ Transpose[{Characters@sentence, Range@StringLength@sentence}] Commented Sep 20, 2019 at 18:15
• Thanks to all for your help and answers. I was looking for something like what Bob Hanlon suggested. How can I list the associations as in ToCharacterCode (without arrows)?
– Val
Commented Sep 20, 2019 at 18:36

Update:

 MapIndexed[# -> #2[[1]] &, Characters[sentence]]


{"h" -> 1, "e" -> 2, "l" -> 3, "l" -> 4, "o" -> 5, " " -> 6, "w" -> 7, "o" -> 8, "r" -> 9, "l" -> 10, "d" -> 11, "!" -> 12}

To get the numbers only the simplest way is what @MassDefect suggested in a comment above: Range @ StringLength @ sentence.

You can use ToCharacterCode:

ToCharacterCode[sentence]


{104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33}

FromCharacterCode[%]


"hello world!"

Normal @ AssociationThread[Characters[sentence], ToCharacterCode[sentence]]


{"h" -> 104, "e" -> 101, "l" -> 108, "o" -> 111, " " -> 32, "w" -> 119, "r" -> 114, "d" -> 100, "!" -> 33}

List @@@ Normal @


{{"h", 104}, {"e", 101}, {"l", 108}, {"o", 111}, {" ", 32}, {"w", 119}, {"r", 114}, {"d", 100}, {"!", 33}}

Alternatively,

DeleteDuplicates @ Thread[{Characters[sentence], ToCharacterCode[sentence]}]


or

Thread[{#, Flatten @ ToCharacterCode[#]}] & @ DeleteDuplicates[Characters @ sentence]


both give

{{"h", 104}, {"e", 101}, {"l", 108}, {"o", 111}, {" ", 32}, {"w", 119}, {"r", 114}, {"d", 100}, {"!", 33}}