Python translate with multiple characters

天大地大妈咪最大 提交于 2019-12-07 18:32:51

问题


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


回答1:


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'



回答2:


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)



回答3:


You can use a list comprehension, format and map:

>>> s='ABCXYZ'
>>> [format(oc, '02d') for oc in map(ord, s)]
['65', '66', '67', '88', '89', '90']

Then rejoin that into a single string if you wish:

>>> ''.join([format(oc, '02d') for oc in map(ord, s)])
'656667888990'



回答4:


Recent I had same issues like Sam's. So I googled some keywords and fount my solutions.

http://code.activestate.com/recipes/81330-single-pass-multiple-replace/

Btw, this method maybe a little bit slower, but useful for my cases.

Hope it would be helpful to you, and sorry for my bad English.



来源:https://stackoverflow.com/questions/25202007/python-translate-with-multiple-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!