如何将字符串列表转换为bytearray,再将指定元素还原为字符串
实现方法
你采用的是|作为分隔符拼接字符串列表后转bytearray的方案,还原目标字符串只要做逆操作即可,另外你原代码存在变量名笔误,len()里的byte_array需要替换为你前面定义的test_array。
完整可运行代码如下:
test_list = ['Hello', 'World'] a = '|'.join(test_list) test_array = bytearray(a.encode('utf-8')) print(test_array) # 修正原代码变量名笔误 print("Count of bytes:", len(test_array)) # 还原"Hello"字符串 # 1. 将bytearray用utf-8解码为拼接后的完整字符串 decoded_full_str = test_array.decode("utf-8") # 2. 按拼接用的分隔符|拆分回原始列表 original_list = decoded_full_str.split("|") # 3. 取对应位置的元素即可,不知道索引也可以过滤匹配目标值 target = original_list[0] # 未知索引时的匹配写法:target = next(item for item in original_list if item == "Hello") print(target) # 输出:Hello print(type(target)) # 输出:<class 'str'>
注意:该方案仅适用于原始列表所有元素都不包含分隔符|的场景,如果原始内容可能存在|,需要更换为原始内容中不会出现的特殊分隔符,或者改用json序列化等更通用的方案。
内容的提问来源于stack exchange,提问作者JJ Cauton
相关产品推荐
相关产品推荐

