There is a function that takes an argument in the form of a string consisting of "A", "a", "B" and "b".

Each "B" must be replaced by "A", each "A" by "B" and also with a lower register.

Example:

>> swap('ААббББаа') 'ББааААбб' 

Wrote such a weak code, but working:

 def swap(text): new_text = [] for c in text: if c == 'а': new_text.append('б') elif c == 'б': new_text.append('а') elif c == 'А': new_text.append('Б') elif c == 'Б': new_text.append('А') return ''.join(new_text) 

Question: how can you solve this problem differently? So that the code is shorter and / or faster.

    1 answer 1

    If processing speed is important, then I recommend using translate :

     trantab = str.maketrans('АБаб', 'БАба') text = 'ААббББаа' print(text.translate(trantab)) 

    Result:

     ББааААбб 
    • Thank! This method is probably the best. I did this: def swap(text): tab = str.maketrans('АБаб', 'БАба'); return text.translate(tab) def swap(text): tab = str.maketrans('АБаб', 'БАба'); return text.translate(tab) - Nikolay
    • @ Nikolai, always welcome. It seems to me that in this case there is not much point in making it out as a function, especially if you plan to call it often, because str.maketrans() it makes sense to call only once for the same character sets - MaxU
    • 2
      str.maketrans() : it is worth noting that str.maketrans() works only for letters that are represented with one character (Unicode code point) in the line ( 'ё' U + 0435 U + 0308 will have to be normalized first). For example, to make Unicode emoticons in ascii convert: 'smiling ☺ frowning ☹'.translate({ord('☺'): ':)', ord('☹'): ':('}) result: 'smiling :) frowning :(' . In the opposite direction already (2 characters in 1) str.translate() does not work. You can use "text :)".replace(":)", "☺") , the result is: 'text ☺' - jfs