If语句判断是一个字符串还是字符串列表。

13 浏览
0 Comments

If语句判断是一个字符串还是字符串列表。

这个问题在这里已经有了答案:

确定对象类型? 【重复】

我有下面的函数。理想情况下,我希望有一个单一字符串或一个字符串列表作为输入。无论哪种情况,我都需要在上面使用 .upper。但是,当只传递一个单一字符串时,迭代器会遍历每个字符。如何编写 if 语句来测试字符串列表或单个字符串?(我无法避免字符串的 iterable 特性)

def runthis(stringinput):
    for t in stringinput:
        t = t.upper()

admin 更改状态以发布 2023年5月21日
0
0 Comments

你可以使用 isinstance() 函数来检查你的函数参数是否是列表类型:\n

def to_upper(arg):
    if isinstance(arg, list):
        return [item.upper() for item in arg]  # This is called list comprehension
    else:
        return arg.upper()

0
0 Comments

使用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

0