You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.6中如何打印变量类型且不显示'class'字样?

Solution to Extract Full Class Name from Type Object

Got it, let's sort this out! When you run print(type(list(soup.children)[0])), you're printing a list containing a type object, which is why you get the wrapped output [<class 'bs4.element.Tag'>]. To get just the bs4.element.Tag string like you see when directly evaluating type(list(soup.children)[0]) in the command line, here are two reliable approaches:

Python's type objects have built-in attributes to access the module and class name directly. This is the most robust method since it doesn't rely on string formatting that might change:

# Get the type object first
element_type = type(list(soup.children)[0])
# Combine module and class name for the full path
print(f"{element_type.__module__}.{element_type.__name__}")

This will output exactly bs4.element.Tag — perfect for what you need. If you only wanted the short class name (like Tag), you could just use element_type.__name__.

Option 2: String Manipulation

If you prefer a quick hack, you can convert the type object to a string and extract the part you need:

type_string = str(type(list(soup.children)[0]))
# Split the string on single quotes and grab the middle segment
print(type_string.split("'")[1])

This works because the default string representation of a type is <class 'module.class'>, so splitting on ' gives us a list where the second element is the full class path.

Why Your Original Output Looked Different

When you directly enter type(list(soup.children)[0]) in the command line, Python uses its default repr() output for the type object. But when you wrap it in a list and print the list, you're seeing the repr() of the list containing the type object — hence the extra brackets and full class wrapper text.

内容的提问来源于stack exchange,提问作者Ohad Rozen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:13:27