Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python translate with multiple characters

I am trying to create a program in python 3.3.3 that will take a string then turn it into numbers (1-26)

I know how to do it for one digit but not 2

translist = str.maketrans("123456789", "ABCDEFGHI")

Is there a way to do this

like image 206
samrobbins Avatar asked Dec 25 '22 05:12

samrobbins


2 Answers

You cannot do what you want with str.translate(); that only works for one-on-one replacements. You are trying to replace one character with two different characters here.

You could use a regular expression instead:

re.sub('[A-Z]', lambda m: str(ord(m.group()) - 64), inputstring)

This takes the ASCII codepoint of each letter and subtracts 64 (A is 65 in the ASCII standard).

Note that this can lead to some confusing ambiguous interpretations:

>>> import re
>>> inputstring = 'FOO BAR BAZ'
>>> re.sub('[A-Z]', lambda m: str(ord(m.group()) - 64), inputstring)
'61515 2118 2126'

Is that 6 1 5 1 5 or 6 15 15 for the first set of numbers? You may want to 0-pad your digits:

re.sub('[A-Z]', lambda m: format(ord(m.group()) - 64, '02d'), inputstring)

which produces:

>>> re.sub('[A-Z]', lambda m: format(ord(m.group()) - 64, '02d'), inputstring)
'061515 020118 020126'
like image 156
Martijn Pieters Avatar answered Dec 28 '22 07:12

Martijn Pieters


By no mean am I the best Python programmer (still beginning my journey), however this code seems to do what you want.

Firstly, make a dictionary like so:

abc = {"A": "1",
   "B": "2",
   "C": "3",
   "D": "4",
   "E": "5",
   "F": "6",
   "G": "7",
   "H": "8",
   "I": "9",
   "J": "10",
   "K": "11",
   "L": "12",
   "M": "13",
   "N": "14",
   "O": "15", 
   "P": "16",
   "Q": "17",
   "R": "18",
   "S": "19",
   "T": "20",
   "U": "21",
   "V": "22",
   "W": "23",
   "X": "24",
   "Y": "25",
   "Z": "26"}

Then you could do so:

txt = str(input("Text: ")).upper()
ntxt = ""

for char in txt:
    if char in abc:
        ntxt += abc[char]
    else:
        ntxt += char

print("New string:", ntxt)
like image 22
TheShanoGamer Avatar answered Dec 28 '22 06:12

TheShanoGamer