Reputation: 23223
I'm using Python standard logging module with custom formatter where I limit length of some fields. It uses standard %
Python operator.
I can apply limit for percent-formatted string like this (this limits length to 10 chars):
>>> "%.10s" % "Lorem Ipsum"
'Lorem Ipsu'
Is it possible to trim it from the beginning, so the output is 'orem Ipsum'
(without manipulating right-side argument)?
Upvotes: 15
Views: 52604
Reputation: 368
The equivalent to "%.10s" % "Lorem Ipsum"
in modern Python would be:
Using str.format
:
"{:.10}".format("Lorem Ipsum")
Using f-strings:
text = "Lorem Ipsum"
f"{text:.10}"
Upvotes: 4
Reputation: 595
I had the same question and came up with this solution using LogRecordFactory.
orig_factory = logging.getLogRecordFactory()
def record_factory(*args, **kwargs):
record = orig_factory(*args, **kwargs)
record.sname = record.name[-10:] if len(
record.name) > 10 else record.name
return record
logging.setLogRecordFactory(record_factory)
Here I am truncating the name to 10 characters and storing it in the attribute sname, which can be used as any other value.
%(sname)10s
It is possible to store the truncated name in record.name, but I wanted to keep the original name around too.
Upvotes: 5
Reputation: 395195
Python's % formatting comes from C's printf.
Note that the .
indicates precision for a float. That it works on a string is a mere side effect, and unfortunately, there is no provision in the string formatting specification to accommodate stripping a string from the left to a fixed max width.
Therefore if you must strip a string to a fixed width from the end, I recommend to slice from a negative index. This operation is robust, and won't fail if the string is less than 10 chars.
>>> up_to_last_10_slice = slice(-10, None)
>>> 'Lorem Ipsum'[up_to_last_10_slice]
'orem Ipsum'
>>> 'Ipsum'[up_to_last_10_slice]
'Ipsum'
str.format
also no helpstr.format
is of no help here, the width is a minimum width:
>>> '{lorem:>10}'.format(lorem='Lorem Ipsum')
'Lorem Ipsum'
>>> '{lorem:*>10}'.format(lorem='Lorem')
'*****Lorem'
(The asterisk, "*
", is the fill character.)
Upvotes: 15
Reputation: 63747
This can easily be done through slicing, so you do not require any string format manipulation to do your JOB
>>> "Lorem Ipsum"[-10:]
'orem Ipsum'
Upvotes: 13