Python3将所有字符转换为HTML实体 [英] Python3 Convert all characters to HTML Entities

查看:116
本文介绍了Python3将所有字符转换为HTML实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python3,我想知道是否存在用于将文本的所有字符转换为html实体(甚至包括字母和数字)的模块或默认函数,因为我不想为此创建翻译映射

I'm using Python3 and I wonder if there is a module or a default function for converting all characters of a text to html entities (even the letters and digits) because I don't want to make a translation map for this.

已解决:正如@justhalf告诉我的那样,我通过执行以下功能找到了解决方案:

Solved: As @justhalf told me, I found the solution by making this function:

def htmlEntities( string ):
    return ''.join(['&#{0};'.format(ord(char)) for char in string])

推荐答案

如果要真正转义所有字符,则没有默认功能,但是您可以手动将每个字符替换为普通字符:

If you want to really escape all characters, there is no default function for that, but you can just replace each character with the ordinals manually:

''.join('&%d;'.format(ord(x)) for x in string)

这篇关于Python3将所有字符转换为HTML实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆