如果声明是否有一个字符串或字符串列表[重复](If statement on whether one string, or list of strings [duplicate])

编程入门 行业动态 更新时间:2024-10-25 18:28:05
如果声明是否有一个字符串或字符串列表[重复](If statement on whether one string, or list of strings [duplicate])

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

确定对象的类型? 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 answers

I 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.

更多推荐

本文发布于:2023-07-31 01:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340571.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   有一个   声明   列表   statement

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!