python - 如何仅使用 str.format 在 python3 中截断和填充?

标签 python string python-3.x

我想这样做:

'{pathname:>90}'.format(pathname='abcde')[-2:]

使用字符串格式而不是数组索引。 所以结果将是“de” 或者在 pathname='e' 的情况下,结果将是 ' e',e 之前有一个空格。如果索引是 [2:] 这个问题将由 How to truncate a string using str.format in Python? 回答

我在以下示例中需要这个:

import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO,style='{',format='{pathname:>90}{lineno:4d}{msg}')
logging.info('k')

最佳答案

精度技巧(使用精度格式)不起作用。仅适用于截断字符串的末尾。

解决方法是在将字符串传递给 str.format 之前对字符串进行切片:

>>> '{pathname:>2}'.format(pathname='abcde'[-2:])
'de'
>>> '{pathname:>2}'.format(pathname='e'[-2:])
' e'

由于您无法控制传递给 format 的参数,因此您可以创建 str 的子类并重新定义 format,以便当它满足 pathname 时它截断关键字参数,然后调用原始 str.format 方法。

小型独立示例:

class TruncatePathnameStr(str):
    def format(self,*args,**kwargs):
        if "pathname" in kwargs:
            # truncate
            kwargs["pathname"] = kwargs["pathname"][-2:]
        return str.format(self,*args,**kwargs)

s = TruncatePathnameStr('##{pathname:>4}##')

print(s.format(pathname='abcde'))

打印:

##  de##

在现实生活中使用它:

logging.basicConfig(stream=sys.stdout, level=logging.INFO,style='{',
                    format=TruncatePathnameStr('{pathname:>90}{lineno:4d}{msg}'))

关于python - 如何仅使用 str.format 在 python3 中截断和填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48559775/

相关文章:

python - Python 中惯用的文件级注释?

python - 捕获 MainLoop 异常并在 MessageDialogs 中显示它们

string - 在 Julia 中搜索字符串并返回条件输出的最佳方法?

c# - 在 C# 中从字符串创建动态类型

python - 从边界生成移动物体

python - 从数据帧中的第一行中减去每一行

c++ - 将 UTC 格式的字符串转换为 Unix time_t 时,实际的时间戳和秒数是多少?

mysql - 解析 mysql.log 文件

python-3.x - 为什么 docker 寻找/简单的 python 包?

python - 在垃圾收集后保留循环引用