从已排序的字典键中仅删除前导零

Remove only leading zeros from sorted dictionary keys

这是我的代码

file_name = input()

shows = {}


with open(file_name, 'r') as file:
    lines = file.readlines()
    for i in range(0, len(lines), 2):
        season = lines[i].strip('\n')
        name = lines[i+1].strip('\n')
        if(season in shows):
            shows[season].append(name)
        else:
            shows[season] = [name]
    
    
    with open('output_keys.txt', 'w+') as f:
        for key in sorted (shows.keys()):
            f.write('{}: {}\n'.format(key, '; '.join(shows.get(key))))
            print('{}: {}'.format(key, '; '.join(shows.get(key))))
      
    titles = []      
    for title in shows.values():
        titles.extend(title)
        
    with open('output_titles.txt', 'w+') as f:
        for title in sorted(titles):
            f.write('{}\n'.format(title))
            print(title)
        
            

问题出在我的 output_keys 文件上,前导零是唯一不同的输出:

我试过在密钥后使用 .strip('0') 但那样也会删除尾随零并弄乱以零结尾的数字。

我认为你需要更改这一行:

f.write('{}: {}\n'.format(key, '; '.join(shows.get(key))))

对此:

f.write('{}: {}\n'.format(key.lstrip("0"), '; '.join(shows.get(key))))

lstrip("0") 将删除 "0" 仅当它作为字符串的 start/left 时。

这里有一些例子可以更清楚地说明这一点:

>>>"07: Gone with the Wind, Rocky".lstrip('0')
'7: Gone with the Wind, Rocky'
>>>"17: Gone with the Wind, Rocky".lstrip('0')
'17: Gone with the Wind, Rocky'