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wB?{@SqDA_AQwDAw@g@DEGAu@B}BA}@Fy@Re@Hw@A_AUiAH{@RYXk@EwBG{@OiAAmA

So you can see @xAD~@ becomes @­~@ when I would expect it to be @\xAD~@.

Advertisement

Answer

The basic problem is that there are no backslashes in your string. Your source code has backslashes, but they are all escape signals. If you want to retain the backslashes in “WYSIWYG” style, use raw string mode:

txt = r"qnkyHbgFYhB..."

This will retain the characters as seen, without processing the usual escape sequences.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement