Increment number in string

后端 未结 5 1629
孤独总比滥情好
孤独总比滥情好 2021-01-14 09:14

I am trying to get the following output until a certain condition is met.

test_1.jpg
test_2.jpg
..
test_50.jpg

The solution (if you could remotely call

相关标签:
5条回答
  • 2021-01-14 09:23

    Update for Python v3.6+ - using formatted string literals:

    for n in range(1,51):
        print(f'test_{n}')
    
    0 讨论(0)
  • 2021-01-14 09:25

    It's probably easiest to keep dstPath something like "test_%d.jpg", and just pass it a varying count:

    dstPath = "test_%d.jpg"
    i = 1
    while os.path.exists(dstPath % i):
        i += 1
    dstPath = dstPath % i # Final name
    
    0 讨论(0)
  • 2021-01-14 09:46

    Print out the value of parts[0] each time you go round the loop ... I think you may be surprised,

    0 讨论(0)
  • 2021-01-14 09:47

    It seems as though your condition os.path.exists(dstPath) is matching the same renamed file multiple times. So for example, it renames test.jpg to test_1.jpg; then renames test_1.jpg to test_1_2.jpg, etc.

    0 讨论(0)
  • 2021-01-14 09:47
    for j in range(1,10):
        print("test_{0}.jpg".format(j))
    

    enter image description here

    0 讨论(0)
提交回复
热议问题