- Use Unicode strings.
- Declare your source encoding.
- Use the characters directly in the file if you like instead of escape codes.
- For printing, just print the Unicode string.
- For files, use
io.open
, declare the encoding (can be different than source and console), and write Unicode strings.
- Save the source in the source encoding.
Then, if your console encoding supports the character (even if the console is a different encoding than the source file), it will display correctly. Files will contain the correctly encoded character.
Example (works in Python 2 and 3):
#coding:utf8
from __future__ import unicode_literals,print_function
import io
count = 57
with io.open('out.txt','w',encoding='utf8') as fw:
fw.write("Number of files processed within 512±1 samples: {}".format(count))
print("Number of files processed within 512±1 samples: {}".format(count))
Output:
C:\temp>chcp # Console is a different encoding!
Active code page: 437
C:\temp>py -2 x.py # Python 2 displays correctly
Number of files processed within 512±1 samples: 57
C:\temp>py -3 x.py # Python 3 displays correctly
Number of files processed within 512±1 samples: 57
C:\temp>chcp 65001 # Change to output file encoding (UTF-8)
Active code page: 65001
C:\temp>type out.txt # Content of file is correct.
Number of files processed within 512±1 samples: 57