Python字符串格式化:不同字段名类型下如何得到‘the value is int’结果?
How to get 'the value is int' via Python string formatting with a dictionary
Alright, let's break this down. Suppose you have a dictionary (say, something like data = {"value": 42} where the value is an integer), and you want to format a string to output 'the value is int'. Here are a few straightforward ways to do it:
Using f-strings (Python 3.6+)
This is the cleanest and most modern approach. We'll grab the type of the dictionary's value, then get its name as a string:
data = {"value": 42} output = f"the value is {type(data['value']).__name__}" print(output) # Output: the value is int
Quick explanation:
type(data['value'])returns the type object of the value (in this case,<class 'int'>).- The
.__name__attribute pulls out the human-readable name of that type as a plain string ('int').
Using str.format() (compatible with older Python versions)
If you're working with Python 3.5 or earlier, this method is reliable. You can either precompute the type name or calculate it directly in the format call:
Option 1: Precompute and add the type name to your dictionary
data = {"value": 42} data["type_name"] = type(data["value"]).__name__ output = "the value is {type_name}".format(**data) print(output) # Output: the value is int
Option 2: Calculate directly in the format invocation
data = {"value": 42} output = "the value is {t.__name__}".format(t=type(data["value"])) print(output) # Output: the value is int
Key notes
- This works dynamically: if your dictionary's value was a string (like
"hello"), it would automatically output'the value is str'instead. - Double-check that the key you're accessing in the dictionary exists—otherwise you'll hit a
KeyError.
内容的提问来源于stack exchange,提问作者Afshin
相关产品推荐
相关产品推荐

