简体   繁体   English

Python字符串格式 - 限制字符串长度,但修剪字符串开头

[英]Python string formatting - limit string length, but trim string beginning

I'm using Python standard logging module with custom formatter where I limit length of some fields. 我正在使用带有自定义格式化程序的Python标准日志记录模块,其中我限制了某些字段的长度。 It uses standard % Python operator. 它使用标准的% Python运算符。

I can apply limit for percent-formatted string like this (this limits length to 10 chars): 我可以像这样对百分比格式的字符串应用限制(这会将长度限制为10个字符):

>>> "%.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 )? 是否有可能从头开始修剪它,所以输出是'orem Ipsum'没有操纵右侧参数 )?

This can easily be done through slicing, so you do not require any string format manipulation to do your JOB 这可以通过切片轻松完成,因此您不需要任何字符串格式操作来执行您的JOB

>>> "Lorem Ipsum"[-10:]
'orem Ipsum'

Is it possible to trim it from the beginning with % formatting? 是否可以从%格式开始修剪它?

Python's % formatting comes from C's printf . Python的%格式来自C的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. 此操作非常强大,如果字符串小于10个字符,则不会失败。

>>> 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 help str.format也没有帮助

str.format is of no help here, the width is a minimum width: str.format在这里没有帮助,宽度是最小宽度:

>>> '{lorem:>10}'.format(lorem='Lorem Ipsum')
'Lorem Ipsum'
>>> '{lorem:*>10}'.format(lorem='Lorem')
'*****Lorem'

(The asterisk, " * ", is the fill character.) (星号“ * ”是填充字符。)

I had the same question and came up with this solution using LogRecordFactory. 我有同样的问题,并使用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. 在这里,我将名称截断为10个字符并将其存储在属性sname中,该属性可以用作任何其他值。

%(sname)10s

It is possible to store the truncated name in record.name, but I wanted to keep the original name around too. 可以将截断的名称存储在record.name中,但我也希望保留原始名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM