检查输入是字符串列表/元组还是单个字符串

发布于 2024-07-23 01:48:35 字数 227 浏览 5 评论 0原文

我有一种方法,我希望能够接受单个字符串(一条路径,但不一定是运行代码的计算机上存在的路径)或字符串列表/元组。

鉴于字符串充当字符列表,我如何判断该方法收到的是哪种类型?

我希望能够接受单个条目的标准或 unicode 字符串,以及多个条目的列表或元组,所以 isinstance 似乎不是答案,除非我错过了一个巧妙的技巧(比如采用共同祖先类的优势?)。

Python版本是2.5

I've a method that I want to be able to accept either a single string (a path, but not necessarily one that exists on the machine running the code) or a list/tuple of strings.

Given that strings act as lists of characters, how can I tell which kind the method has received?

I'd like to be able to accept either standard or unicode strings for a single entry, and either lists or tuples for multiple, so isinstance doesn't seem to be the answer unless I'm missing a clever trick with it (like taking advantage of common ancestor classes?).

Python version is 2.5

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

怂人 2024-07-30 01:48:36

isinstance is 一个选项:

In [2]: isinstance("a", str)
Out[2]: True

In [3]: isinstance([], str)
Out[3]: False

In [4]: isinstance([], list)
Out[4]: True

In [5]: isinstance("", list)
Out[5]: False

isinstance is an option:

In [2]: isinstance("a", str)
Out[2]: True

In [3]: isinstance([], str)
Out[3]: False

In [4]: isinstance([], list)
Out[4]: True

In [5]: isinstance("", list)
Out[5]: False
唯憾梦倾城 2024-07-30 01:48:36

类型检查:

def func(arg):
    if not isinstance(arg, (list, tuple)):
        arg = [arg]
    # process

func('abc')
func(['abc', '123'])

可变参数:

def func(*arg):
    # process

func('abc')
func('abc', '123')
func(*['abc', '123'])

Type checking:

def func(arg):
    if not isinstance(arg, (list, tuple)):
        arg = [arg]
    # process

func('abc')
func(['abc', '123'])

Varargs:

def func(*arg):
    # process

func('abc')
func('abc', '123')
func(*['abc', '123'])
梓梦 2024-07-30 01:48:36

因为我喜欢让事情变得简单,所以这里是与 2.x 和 3.x 兼容的最短形式:

# trick for py2/3 compatibility
if 'basestring' not in globals():
   basestring = str

v = "xx"

if isinstance(v, basestring):
   print("is string")

As I like to keep things simple, here is the shortest form that is compatible with both 2.x and 3.x:

# trick for py2/3 compatibility
if 'basestring' not in globals():
   basestring = str

v = "xx"

if isinstance(v, basestring):
   print("is string")
乄_柒ぐ汐 2024-07-30 01:48:36
>>> type('abc') is str
True
>>> type(['abc']) is str
False

此代码与 Python 2 和 3 兼容

>>> type('abc') is str
True
>>> type(['abc']) is str
False

This code is compatible with Python 2 and 3

只是我以为 2024-07-30 01:48:36

我很惊讶没有人给出鸭子类型的答案,但给出了不清楚或高度依赖于类型或依赖于版本的答案。 另外,遗憾的是,所接受的答案有针对 Python 2 和 3 的单独代码。Python 使用并鼓励鸭子类型,因此(比 sorin 的“最短形式”多一行,这不是鸭子类型)我建议:

def is_str(v):
    return hasattr(v, 'lower')

...以及任何其他属性你想使用(记住引号)。 这样,使用您的软件的客户端代码就可以发送他们想要的任何类型的字符串,只要它具有您的软件所需的接口即可。 鸭子类型对于其他类型来说更有用,但通常是最好的方法。

或者您也可以这样做(或者通常检查 AttributeError 并采取其他操作):

def is_str(v):
    try:
        vL = v.lower()
    except AttributeError:
        return False
    return True

I'm surprised no one gave an answer with duck typing, but gave unclear or highly type-dependent or version-dependent answers. Also, the accepted answer unfortunately has separate code for Python 2 and 3. Python uses and encourages duck typing, so (one line more than sorin's "shortest form" which is not duck typing) I instead recommend:

def is_str(v):
    return hasattr(v, 'lower')

...and whatever other attributes you want to use (remember the quotes). That way, client code using your software can send whatever kind of string they want as long as it has the interface your software requires. Duck typing is more useful in this way for other types, but it is generally the best way.

Or you could also do this (or generally check for AttributeError and take some other action):

def is_str(v):
    try:
        vL = v.lower()
    except AttributeError:
        return False
    return True
停顿的约定 2024-07-30 01:48:36

使用 isinstance(arg, basestring) 检查类型

Check the type with isinstance(arg, basestring)

战皆罪 2024-07-30 01:48:36

您考虑过 varargs 语法吗? 我不太确定这是否是您要问的,但会类似 这个问题符合你的思路吗?

Have you considered varargs syntax? I'm not really sure if this is what you're asking, but would something like this question be along your lines?

海风掠过北极光 2024-07-30 01:48:36

你能不能这样做:

(i == list (i) or i == tuple (i))

如果输入是元组或列表,它会回复。 唯一的问题是它无法在仅包含一个变量的元组中正常工作。

Can't you do:

(i == list (i) or i == tuple (i))

It would reply if the input is tuple or list. The only issue is that it doesn't work properly with a tuple holding only one variable.

浅唱ヾ落雨殇 2024-07-30 01:48:35

检查变量是字符串还是 unicode 字符串

  • 您可以使用Python 3
    isinstance(some_object, str)
  • : Python 2:
    isinstance(some_object, basestring)

这将为字符串和 unicode 字符串返回 True

当您使用 python 2.5 时,您可以执行以下操作:

if isinstance(some_object, basestring):
    ...
elif all(isinstance(item, basestring) for item in some_object): # check iterable for stringness of all items. Will raise TypeError if some_object is not iterable
    ...
else:
    raise TypeError # or something along that line

紧张可能不是一个词,但我希望你能明白

You can check if a variable is a string or unicode string with

  • Python 3:
    isinstance(some_object, str)
  • Python 2:
    isinstance(some_object, basestring)

This will return True for both strings and unicode strings

As you are using python 2.5, you could do something like this:

if isinstance(some_object, basestring):
    ...
elif all(isinstance(item, basestring) for item in some_object): # check iterable for stringness of all items. Will raise TypeError if some_object is not iterable
    ...
else:
    raise TypeError # or something along that line

Stringness is probably not a word, but I hope you get the idea

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文