Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>0) Don't compare to boolean literals. Just use the condition directly.</p> <p>1) Don't write "if &lt;something&gt;" and then "if &lt;not something&gt;". That's what <code>else</code> is for.</p> <p>2) <code>% 2</code> is a clearer parity test than <code>&amp; 1</code>.</p> <p>3) Your logic is wrong: you're subtracting 1 from the even numbers and leaving the odd numbers untouched, so you'd get 1, 1, 3, 3, 5, 5... instead of 1, 1, 2, 2, 3, 3 as desired. You need a division by 2 in there. The simple way is to add 1, divide by 2 (in integer arithmetic, this discards the remainder), and then append either an 'A' or a 'B' according to the parity.</p> <p>4) The error message tells you exactly what's wrong. <code>TypeError: Can't convert 'int' object to str implicitly</code> means exactly what it says. <code>replace</code> replaces some substring in a string with another string. You can't replace an int within the string with another int, because the string doesn't contain ints (it merely contains substrings that can be <strong>interpreted</strong> as ints), and won't store any ints that you try to put into it.</p> <p>Even if you could do this, there would be no way for the implicit conversion to know how many leading zeroes to use in the replacement.</p> <p>The way we deal with this is to convert explicitly, of course. That's what <code>int</code> is doing in your code: explicitly converting the string to an integer. The calls to <code>str</code> in your code are useless, because explicitly converting a string to a string does nothing.</p> <p>So the logic is:</p> <p>a) Extract the part we're going to replace, and explicitly convert to int.</p> <p>b) Do math to get the integer part of the replacement.</p> <p>c) Use string formatting to create a string that contains (a) a zero-padded string representation of the new integer; (b) either 'A' or 'B' as a suffix.</p> <p>d) Replace the part we're going to replace with that replacement. Instead of searching for the text again and replacing it, we'll just splice the replacement into where the original was - that's more direct, and avoids mistakes (e.g. if the file name happens to contain another copy of the number earlier on).</p> <pre><code>def make_page_denotation(rename_directory, extension, rename_files): for filename in glob(rename_files): original = int(filename[-9:-4]) # a) new_value = (original + 1) / 2 # b) replacement = ('%05d' % new_value) + ('B' if original % 2 else 'A') # c) new_filename = filename[:-9] + replacement + filename[-4:] # d) os.rename(filename, replacement) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload