在为字符串赋值之前,不能计算字符串的长度,因此在进行替换之前,请先这样做,然后用简单的数学计算出结果的长度:POWERS_OF_TEN = {10**n for n in range(7)} # handle strings over 10M chars long
string = "This is a sentence and it has %d characters"
length = len(string) - len('%d') + len("%d" % len(string))
correction = len(string)+1 in POWERS_OF_TEN
string %= length+correction
print(string) # This is a sentence and it has 43 characters
上面的计算正确地处理了结果的长度与包含"%d"的原始字符串的长度不同的情况。在
下面的测试代码说明了这一点,该代码显示原始字符串及其长度,然后是结果字符串及其实际长度和计算长度(对于不同大小的输入),如您所见,后两个值始终匹配,包括在特殊情况下,添加一个字符会使结果字符串变长两个字符:
^{pr2}$
输出:'%d', len: 2 -> '1', length actual: 1 vs computed: 1
'A%d', len: 3 -> 'A2', length actual: 2 vs computed: 2
'AB%d', len: 4 -> 'AB3', length actual: 3 vs computed: 3
'ABC%d', len: 5 -> 'ABC4', length actual: 4 vs computed: 4
'ABCD%d', len: 6 -> 'ABCD5', length actual: 5 vs computed: 5
'ABCDE%d', len: 7 -> 'ABCDE6', length actual: 6 vs computed: 6
'ABCDEF%d', len: 8 -> 'ABCDEF7', length actual: 7 vs computed: 7
'ABCDEFG%d', len: 9 -> 'ABCDEFG9', length actual: 8 vs computed: 8
'ABCDEFGH%d', len: 10 -> 'ABCDEFGH10', length actual: 10 vs computed: 10
'ABCDEFGHI%d', len: 11 -> 'ABCDEFGHI11', length actual: 11 vs computed: 11
'ABCDEFGHIJ%d', len: 12 -> 'ABCDEFGHIJ12', length actual: 12 vs computed: 12