1写函数,判断用户传入的对象(字符串、列表、元组)长度,并返回给调用者。
时间: 2024-11-15 20:33:08 浏览: 16
你可以创建一个通用的函数,利用Python的内置类型检查功能来确定对象的类型,然后计算其长度。这里有一个示例:
```python
def get_length(obj):
if isinstance(obj, str): # 判断是否为字符串
length = len(obj)
return f"The string has {length} characters."
elif isinstance(obj, (list, tuple)): # 判断是否为列表或元组
length = len(obj)
return f"The list or tuple has {length} elements."
else:
return "The object is not a string, list, or tuple and cannot be measured for length."
# 测试函数
print(get_length("Hello World")) # 输出: The string has 11 characters.
print(get_length([1, 2, 3, 4])) # 输出: The list or tuple has 4 elements.
print(get_length((5, 6, 7))) # 输出: The list or tuple has 3 elements.
try:
print(get_length(8)) # 输出: The object is not a string, list, or tuple and cannot be measured for length.
except TypeError:
pass # 如果传入非预期类型,捕获异常并忽略
```
这个函数首先检查输入对象的类型,如果是字符串就计算字符数,如果是列表或元组则计算元素数。如果对象不是这三种类型之一,它会返回一条错误消息。
阅读全文