欢迎访问宙启技术站
智能推送

使用Python编写的to_text()函数来将文本数据转换为字符串的完整代码示例

发布时间:2023-12-25 14:39:21

下面是一个使用Python编写的to_text()函数的示例代码,它将文本数据转换为字符串:

def to_text(data):
    if isinstance(data, str):
        return data
    elif isinstance(data, bytes):
        return data.decode('utf-8')
    elif isinstance(data, list):
        return '
'.join(data)
    elif isinstance(data, dict):
        return '
'.join([f'{key}: {value}' for key, value in data.items()])
    else:
        return str(data)

使用例子:

# 转换字符串
text_str = to_text("Hello World!")
print(text_str)  # 输出: Hello World!

# 转换字节数组
text_bytes = to_text(b"Hello World!")
print(text_bytes)  # 输出: Hello World!

# 转换列表
text_list = to_text(['Hello', 'World'])
print(text_list)  # 输出:
# Hello
# World

# 转换字典
text_dict = to_text({'name': 'John', 'age': 30})
print(text_dict)  # 输出:
# name: John
# age: 30

# 转换其他数据类型
text_other = to_text(123)
print(text_other)  # 输出: 123

这个示例代码中的to_text()函数可以处理字符串、字节数组、列表和字典的转换。如果传入的数据类型不属于这些类型中的一个,该函数会将其转换为字符串。