如何查找提供的输入字符串是否为有效字符集?

有没有办法检查给定的字符串变量是否包含有效的字符集名称。


例如:


输入:


str = "utf-8"

#checking str, if valid charset name then return True


str= "abcd"

#checking str, if invalid charset name then return False

有什么方法可以实现吗?


编程语言 Python。


HUX布斯
浏览 233回答 1
1回答

忽然笑

我读你的问题是想验证一个字符串是一个有效的编码名称。 codecs.lookup(encoding)可以做到这一点:>>> import codecs>>> codecs.lookup('utf-8')<codecs.CodecInfo object for encoding utf-8 at 0x1e7c42905e8>>>> codecs.lookup('abcd')Traceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>LookupError: unknown encoding: abcd所以你可以使用:def validate(name):&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; codecs.lookup(name)&nbsp; &nbsp; &nbsp; &nbsp; return True&nbsp; &nbsp; except LookupError:&nbsp; &nbsp; &nbsp; &nbsp; return False
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python