如何在Python中使用str.format截断字符串? - python

如何在Python中使用 str.format 截断字符串?可能吗?

Format Specification Mini-Language中提到了一个width参数:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
...
width       ::=  integer
...

但是指定它显然仅适用于填充,而不能截断:

>>> '{:5}'.format('aaa')
'aaa  '
>>> '{:5}'.format('aaabbbccc')
'aaabbbccc'

因此,它实际上是最小宽度,而不是宽度。

我知道我可以切片字符串,但是我在这里处理的数据是完全动态的,包括格式字符串和传入的args。我不能只是去明确地切片一个。

参考方案

使用.precision代替:

>>> '{:5.5}'.format('aaabbbccc')
'aaabb'

根据Format Specification Mini-Language的文档:

精度是一个十进制数字,指示对于使用'f''F'格式化的浮点值,在小数点后或对于对于'g''G'格式化的浮点值,在小数点之前和之后应显示多少位数。 对于非数字类型,该字段指示最大字段大小-换句话说,将从字段内容中使用多少个字符。 整数值不允许使用精度。

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

python JSON对象必须是str,bytes或bytearray,而不是'dict - python

在Python 3中,要加载以前保存的json,如下所示:json.dumps(dictionary)输出是这样的{"('Hello',)": 6, "('Hi',)": 5}当我使用json.loads({"('Hello',)": 6,…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…