If语句判断是一个字符串还是字符串列表。
If语句判断是一个字符串还是字符串列表。
这个问题在这里已经有了答案:
我有下面的函数。理想情况下,我希望有一个单一字符串或一个字符串列表作为输入。无论哪种情况,我都需要在上面使用 .upper。但是,当只传递一个单一字符串时,迭代器会遍历每个字符。如何编写 if 语句来测试字符串列表或单个字符串?(我无法避免字符串的 iterable 特性)
def runthis(stringinput): for t in stringinput: t = t.upper()
admin 更改状态以发布 2023年5月21日
使用isinstance
检查类型。
def runthis(stringinput): if isinstance(stringinput, list): for t in stringinput: t = t.upper() # Some other code should probably be here. elif isinstance(stringinput, basestring): t = t.upper() # Some other code perhaps as well. else: raise Exception("Unknown type.")
在Python 3中使用str
而不是basestring
。