Skip to main content
 首页 » 编程设计

python之格式化字典中键的输出

2025年05月04日11Terrylee

我有一个字典,它存储一个字符串作为键,一个整数作为值。在我的输出中,我希望将 key 显示为不带括号或逗号的字符串。我该怎么做?

for f_name,f_loc in dict_func.items(): 
        print ('Function names:\n\n\t{0} -- {1} lines of code\n'.format(f_name, f_loc)) 

输出:

Enter the file name: test.txt 
line = 'def count_loc(infile):' 
 
There were 19 lines of code in "test.txt" 
 
Function names: 
 
    ('count_loc(infile)',) -- 15 lines of code 

如果不清楚,我希望输出的最后一行显示为:

count_loc(infile) -- 15 lines of code 

编辑

name = re.search(func_pattern, line).groups() 
name = str(name) 

在我的输出之前使用 type(),我验证它仍然是一个字符串,但输出与 name 是一个元组时一样

请您参考如下方法:

我没有 Python 3,所以我无法测试它,但是 f_name 的输出让它看起来像是一个包含一个元素的元组。因此,您可以将 .format(f_name, f_loc) 更改为 .format(f_name[0], f_loc)

编辑:

为响应您的编辑,请尝试使用 .group()而不是 .groups()