Formatting strings, either with the %
operator or str.format
method, requires a valid string and arguments matching this
string’s replacement fields.
This rule raises an issue when formatting a string will raise an exception because the input string or arguments are invalid. Rule
S3457 covers cases where no exception is raised and the resulting string is simply not formatted properly.
Noncompliant code example
print('Error code %d' % '42') # Noncompliant. Replace this value with a number as %d requires.
print('User {1} is not allowed to perform this action'.format('Bob')) # Noncompliant. Replacement field numbering should start at 0.
print('User {0} has not been able to access {}'.format('Alice', 'MyFile')) # Noncompliant. Use only manual or only automatic field numbering, don't mix them.
print('User {a} has not been able to access {b}'.format(a='Alice')) # Noncompliant. Provide a value for field "b".
Compliant solution
print('Error code %d' % 42)
print('User {0} is not allowed to perform this action'.format('Bob'))
print('User {0} has not been able to access {1}'.format('Alice', 'MyFile'))
print('User {a} has not been able to access {b}'.format(a='Alice', b='MyFile'))