开发者

Condense list into string : ['z','y','x'...] -> 'zyx...' ? Python (2.7.1)

开发者 https://www.devze.com 2023-02-27 11:16 出处:网络
If I have list=\'abcdedcba\' and i want: a=z, b=开发者_JS百科y, c=x, d=w, e=v so it would translate to:

If I have list='abcdedcba'

and i want: a=z, b=开发者_JS百科y, c=x, d=w, e=v so it would translate to:

translate='zyxwvwxya'

How would I do this? If I construct a dictionary

>>> d=dict(zip(('a','b','c','d','e'),('z','y','x','w','v')))

and type

>>> example= d[x] for x in list
>>> print translate
['z', 'y', 'x', 'w', 'v', 'w', 'x', 'y', 'z']

How do I get it back into the form

translate='zyxwvwxyz'

?


the_list = ['z', 'y', 'x', 'w', 'v', 'w', 'x', 'y', 'z']
print "".join(the_list)


For monoalphabetic substitution, use maketrans and translate from the string module. They operate like the unix tr command. Joining with an empty separator is the correct answer for that last step, but not necessary for this exact task.


''.join(translate)

I'm not sure this is what you want?


an example of using maketrans and translate:

>>> import string
>>> table = string.maketrans('abcdef', 'zyxwvu')
>>> 'abdedddfdffdabe'.translate(table)
'zywvwwwuwuuwzyv'

Assuming you want to substitute all letters in the ASCII alphabet:

import string
reversed_ascii_letters = string.ascii_letters[::-1]
# reorder lowercase and uppercase
reversed_ascii_letters = reversed_ascii_letters[26:] + reversed_ascii_letters[:26]
table = string.maketrans(string.ascii_letters, reversed_ascii_letters)
data = 'The Quick Brown Fox Jumped Over the Lazy Dog'
print data.translate(table)


>>> import string
>>> table = string.maketrans(string.lowercase, string.lowercase[::-1])
>>> 'abcdedcba'.translate(table)
'zyxwvwxyz'


>>> import string
>>> letters = string.lowercase
>>> letters
'abcdefghijklmnopqrstuvwxyz'
>>> def revert_string(s):
    s_rev = ''
    for c in s:
        s_rev += letters[len(letters) - 1 - letters.find(c)]
    return s_rev

>>> s = 'zearoizuetlkzjetkl'
>>> revert_string(s)
'avzilrafvgopaqvgpo'
0

精彩评论

暂无评论...
验证码 换一张
取 消