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

标签 python string list types enumerable

我有以下代码

def printmylist( mylist ):
    """
    print tree
    """
    try:
    for f in mylist:
        printmylist( f )
    except:
        print( "        " + mylist )

希望得到这样的输出:

root
   branch
     leaf
     leaf

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

r
o
o
t
.
.

检查类型似乎不是 Pythonic,那么 Pythonian 会怎么做呢?

最佳答案

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

isinstance(var, types.StringTypes)

或者:

isinstance(var, basestring)

types 的文档module 表示后者是最新版本的 Python 2.x 中的首选方式。

关于Python:通过字符串列表递归 - 如何区分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7499552/

相关文章:

python - 返回一个包含素数的数组,其乘积为 x

python - 如何通过列值唯一标识 csv 中的行,然后检查另一列是否有 "Passed"关键字并打印它

python - 检测循环中的最后一次迭代

python - Matplotlib 在 3d 表面上绘制轮廓

python - 如何将解包运算符 ("*") 与 C 风格字符串格式一起使用?

java - 为什么 Java 不优化 String.split ("regex") 对字符串文字的调用?

list - 为什么用 cons() 和 list() 创建的列表显示不同?

python - 在区域的部分区域添加边框,matplotlib/geopandas

string - 在两个字符串上使用 tcl exec diff 模拟 diff 输出

python - 在python中打印排序和未排序的列表