这个问题在这里已有答案:
确定对象的类型? 9个答案我有以下功能。 理想情况下,我想要一个字符串或一个作为输入传递的字符串列表。 在任何一种情况下,我都需要使用.upper。 但是,当只传递一个字符串时,迭代器会遍历每个字符。 我怎样才能有if语句来测试字符串列表或单个字符串? (我似乎无法避免字符串的可迭代性质)
def runthis(stringinput): for t in stringinput: t = t.upper()This question already has an answer here:
Determine the type of an object? 12 answersI have the following function. Ideally, I want to have either a single string or a list of strings passed as an input. In either case, I need to use .upper on it. But, when only a single string is passed, the iterator iterates through each character. How can I have an if statement that tests whether a list of strings or a single string? (I can't seem to avoid the iterable nature of strings)
def runthis(stringinput): for t in stringinput: t = t.upper()最满意答案
使用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 。
Check the type using 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.")Use str instead of basestring for Python 3.
更多推荐
发布评论