String Formatting in Python

String formatting in Python

The previous answers have used % formatting, which is being phased out in Python 3.0+. Assuming you're using Python 2.6+, a more future-proof formatting system is described here:

http://docs.python.org/library/string.html#formatstrings

Although there are more advanced features as well, the simplest form ends up looking very close to what you wrote:

>>> "[{0}, {1}, {2}]".format(1, 2, 3)
[1, 2, 3]

python string formatting - implicit str() + format specifiers

You could either implement the __format__ method in your object class or place the str() directly in the format string:

print(f"{str(obj):.5}")

see PEP 498 for details.

note that f"{obj!s:.5}" also works but, in that same specification, !s and !r are considered redundant and only maintained for backward compatibility

Python string formatting with variables - different methods

Simply change it to the driver method you detailed at the bottom.

I can't answer why it was done that way as it does not make any sense to do it with concatenated strings.

string formatting not working as expected

If you simply want to truncate the columns at their max length, you can use string slicing before appending them:

description = description[:23]
amount = amount[:7]
transactions.append(f'{description}{amount}')

If the slice exceeds the length of the string, Python just returns the whole string, so this will work even when a string is shorter than your max length.

Which are safe methods and practices for string formatting with user input in Python 3?

It doesn't matter which format you choose, any format and library can have its own downsides and vulnerabilities. The bigger questions you need to ask yourself is what is the risk factor and the scenario you are facing with, and what are you going to do about it.
First ask yourself: will there be a scenario where a user or an external entity of some kind (for example - an external system) sends you a format string? If the answer is no, there is no risk. If the answer is yes, you need to see whether this is needed or not. If not - remove it to eliminate the risk.
If you need it - you can perform whitelist-based input validation and exclude all format-specific special characters from the list of permitted characters, in order to eliminate the risk. For example, no format string can pass the ^[a-zA-Z0-9\s]*$ generic regular expression.

So the bottom line is: it doesn't matter which format string type you use, what's really important is what do you do with it and how can you reduce and eliminate the risk of it being tampered.



Related Topics



Leave a reply



Submit