Search code examples
pythondictionaryord

What does "None for c in" stand for?


I am looking an example code, it said:

subj = 'A.B!c?'
dd = {ord(c):None for c in 'chars_to_remove'}
subj.translate(dd) 

The output is 'A.B!?' . It seems to me ord(c): is a "dictionary", if every element in the string(subj) meets c then c will be removed.

But I cannot get full picture of this statement, I don't understand:

  1. Is c means every element of string?
  2. What does "None for c" means?
  3. If I simply replace "chars_to_remove" to "k", then output will become 'A.B!c?', why?

Please help clear my mind. Thanks.


Solution

  • You are reading it in the wrong way

    {ord(c):None for c in 'chars_to_remove'}
    

    is ord(c):None and for c in 'chars_to_remove'

    for c in 'chars_to_remove' goes through every char in this string 'chars_to_remove'

    ord(c):None when added to the dictionary and used in translate(), it replaces those char to None

    The only char in this String that is in your subj is 'c', so therefore your subj becomes 'A.B!?'