How to print unicode characters with yaml.safe_dump()?
Peter Otten
__peter__ at web.de
Tue May 31 13:38:31 EDT 2016
Peng Yu wrote:
> Hi, The following code shows that "Michał" is printed differently for
> print(yaml.safe_dump(...)) and the direct print. Does anybody know how
> to use yaml.safe_dump() so that "Michał" will be printed as is.
>
> ~$ cat main.py
> #!/usr/bin/env python
> # vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1
> # fileencoding=utf-8:
>
> import yaml
>
> foo = {
> u'first': u"Michał",
> u'last': u"Seweryn",
> }
>
> print foo['first']
>
> print(yaml.safe_dump(foo, default_flow_style=True).encode('utf-8'))
> print(yaml.safe_dump(foo, default_flow_style=False).encode('utf-8'))
> ~$ ./main.py
> Michał
> {first: "Micha\u0142", last: Seweryn}
>
> first: "Micha\u0142"
> last: Seweryn
>
Use the allow_unicode flag:
>>> print yaml.safe_dump(foo, allow_unicode=True, default_flow_style=False)
first: Michał
last: Seweryn
More information about the Python-list
mailing list