Python:通过字符串列表递归 - 如何区分?

1 python string types list enumerable

我有以下代码

def printmylist( mylist ):
    """
    print tree
    """
    try:
    for f in mylist:
        printmylist( f )
    except:
        print( "        " + mylist )
Run Code Online (Sandbox Code Playgroud)

希望获得如下输出:

root
   branch
     leaf
     leaf
Run Code Online (Sandbox Code Playgroud)

但由于字符串是可枚举的,我得到了

r
o
o
t
.
.
Run Code Online (Sandbox Code Playgroud)

检查类型似乎是unpythonic,那么Python将如何解决这个问题呢?

NPE*_*NPE 5

我所知道的最干净的方法是使用types.StringTypes(不要混淆types.StringType):

isinstance(var, types.StringTypes)
Run Code Online (Sandbox Code Playgroud)

或者:

isinstance(var, basestring)
Run Code Online (Sandbox Code Playgroud)

types模块的文档表明后者是最新版本的Python 2.x中的首选方式.