Update: If the output file is a yaml document then you could ignore \u0163
in it. Unicode escapes are valid in yaml documents.
#!/usr/bin/env python3
import json
# json produces a subset of yaml
print(json.dumps('pe toţi mai')) # -> "pe to\u0163i mai"
print(json.dumps('pe toţi mai', ensure_ascii=False)) # -> "pe toţi mai"
Note: no \u
in the last case. Both lines represent the same Python string.
yaml.dump()
has similar option: allow_unicode
. Set it to True
to avoid Unicode escapes.
The url is correct. You don't need to do anything with it:
#!/usr/bin/env python3
from urllib.parse import unquote
url = "pe%20to%C5%A3i%20mai"
text = unquote(url)
with open('some_file', 'w', encoding='utf-8') as file:
def p(line):
print(line, file=file) # write line to file
p(text) # -> pe toţi mai
p(repr(text)) # -> 'pe toţi mai'
p(ascii(text)) # -> 'pe to\u0163i mai'
p("pe to\u0163i mai") # -> pe toţi mai
p(r"pe to\u0163i mai") # -> pe to\u0163i mai
#NOTE: r'' prefix
The \u0163
sequence might be introduced by character encoding error handler:
with open('some_other_file', 'wb') as file: # write bytes
file.write(text.encode('ascii', 'backslashreplace')) # -> pe to\u0163i mai
Or:
with open('another', 'w', encoding='ascii', errors='backslashreplace') as file:
file.write(text) # -> pe to\u0163i mai
More examples:
# introduce some more \u escapes
b = r"pe to\u0163i mai ţţţ".encode('ascii', 'backslashreplace') # bytes
print(b.decode('ascii')) # -> pe to\u0163i mai \u0163\u0163\u0163
# remove unicode escapes
print(b.decode('unicode-escape')) # -> pe toţi mai ţţţ