質問

I'm trying to do a small decoder.
I want to assign the value 'a' to the special letter "("
example: ( = "a"
and if I input "(" it prints it to "a" like:

If I enter "(%!)(":

It prints the equivalent for each character like:

LadyBa

Hope you understand what I mean!
I know it need unicode or something like that but I'm not very good at python
I'm trying to learn.
Working on windows python 3.3

役に立ちましたか?

解決 2

EDIT: this is good, thanks to Ashwini Chaudhary

>>> d = {'(': 'a'}
>>> "".join(d.get(x,x) for x in 'text with m(ny letters')
'text with many letters'

This is a longer solution but does the equivalent:

So you want to translate letters and keep thoos untouched that you do not know?

>>> d = {'(': 'a'}
>>> ''.join(map(lambda letter: d.get(letter, letter), 'text with m(ny letters'))
'text with many letters'

Explanation


This

d.get(letter, letter)

tries to find the letter in d and if not present returns letter (the second letter)


lambda letter: lalala

is the same as

def f(letter):
    return lalala
f # return f

map(function, list) 

does this:

[function(element) for element in list]

which is a short form of

l = []
for element in list:
    l.append(function(element))
l # returns that list

''.join(list)

is the same as

string = ''
for element in list:
    string += element
string # return string as result

他のヒント

you can use str.translate:

In [7]: trans = str.maketrans("(","a")

In [8]: "(bcd(".translate(trans)
Out[8]: 'abcda'

S.translate(table [,deletechars]) -> string

Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256 or None. If the table argument is None, no translation is applied and the operation simply removes the characters in deletechars.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top