我想这样做:
'{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/