代码示例:
def obj_to_str(obj):
"""
将传递的对象转换为字符串。
Args:
obj: 要转换的对象。
Returns:
转换后的字符串。
"""
if isinstance(obj, str):
return obj
elif isinstance(obj, (int, float)):
return str(obj)
elif isinstance(obj, list):
return '[{}]'.format(', '.join(obj_to_str(elem) for elem in obj))
elif isinstance(obj, tuple):
return '({})'.format(', '.join(obj_to_str(elem) for elem in obj))
elif isinstance(obj, dict):
return '{{{}}}'.format(', '.join('{}: {}'.format(obj_to_str(key), obj_to_str(value)) for key, value in obj.items()))
else:
return str(obj)
调用示例:
# 字符串
assert obj_to_str("hello world") == "hello world"
# 整数
assert obj_to_str(123) == "123"
# 浮点数
assert obj_to_str(3.1415) == "3.1415"
# 列表
assert obj_to_str([1, "hello", {"key": "value"}, [2, 3]]) == "[1, hello, {key: value}, [2, 3]]"
# 元组
assert obj_to_str((1, "hello", {"key": "value"}, [2, 3])) == "(1, hello, {key: value}, [2, 3])"
# 字典
assert obj_to_str({"key1": "value1", "key2": [1, 2, 3]}) == "{key1: value1, key2: [1, 2, 3]}"
# 自定义类
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
assert obj_to_str(Person("Rose")) == "Rose"