首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript TextEncoder / TextDecoder等效于python

JavaScript TextEncoder / TextDecoder等效于python
EN

Stack Overflow用户
提问于 2022-11-07 19:22:32
回答 1查看 15关注 0票数 0

我希望通过在javascript上使用TextEncoder和TextDecoder获得相同的结果,但是找不到真正的代码解决方案,而我找到的解决方案并没有给出真正的相同结果。

实例:

代码语言:javascript
复制
const textencoder = new TextEncoder();
console.log(textencoder.encode('$'));
//[36]

const textdecoder = TextDecoder();
console.log(textdecoder.decode(new Uint8Array([36]));
// $
EN

回答 1

Stack Overflow用户

发布于 2022-11-07 19:27:07

经过多次尝试和寻找,我得到了一个朋友的解决方案,我决定与你分享它,也许有一天有人需要它;

代码语言:javascript
复制
class TextEncoder():
    def __init__(self):
        pass
    
    def encode(self, text):
        """
        exp:
            >>> textencoder = TextEncoder()
            >>> textencoder.encode('$')
            >>> [36]
        """
        if isinstance(text, str):
            encoded_text = text.encode('utf-8')
            byte_array = bytearray(encoded_text)
            return list(byte_array)
        else:
            raise TypeError(f'Expecting a str but got {type(text)}')

class TextDecoder():
    def __init__(self):
        pass
    
    def decode(self, array):
        """
        exp:
            >>> textdecoder = TextDecoder()
            >>> textdecoder.decode([36])
            >>> $
        """
        if isinstance(array, list):
            return bytearray(array).decode('utf-8')
        elif isinstance(array, bytearray):
            return array.decode('utf-8')
        else:
            raise TypeError(f'expecting a list or bytearray got: {type(array)}')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74351880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档