简体   繁体   中英

Remove only leading zeros from sorted dictionary keys

This is my code

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)
        
            

The problem is with my output_keys files, leading zeros is the only differing output:

前导零是唯一不同的输出

I've tried using .strip('0') after the key But then that also removes the trailing zero and messes up the numbers that end in zero.

I think you need to change this line:

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

to this:

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

lstrip("0") will remove a "0 " only if it as the start/left of a string.

Here are some examples to make that clearer:

>>>"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'

i know this is really old, but the lstrip worked for me like a charm. My code is way different that the example above, but I was able to determine where in my code i needed to put the lstrip and it worked on my first run. Thank you for saving my brain from reaching a melt down trying to figure out what I needed to do!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM