fra*_*nds 0 python string format
使用"旧"格式化语法,我可以截断字符串中的长整数,如下所示:
'%-5.5s' % 4257647474747
Run Code Online (Sandbox Code Playgroud)
哪个产生 42576
如果我尝试做同样的事情format():
'{:<5.5}'.format(4257647474747)
Run Code Online (Sandbox Code Playgroud)
我收到了错误 ValueError: Precision not allowed in integer format specifier
我需要能够截断传入的数字,因为它必须适合固定大小的字符串.有没有办法用格式截断整数?
将s在'%-5.5s'转换参数与字符串str,然后应用%s的解释了-5.5.你在format通话中没有做任何类似的事情,所以你得到了int类型的解释<5.5.
在格式化之前将整数转换为字符串:
'{:<5.5}'.format(str(4257647474747))
Run Code Online (Sandbox Code Playgroud)
或者使用!s格式字符串来做同样的事情:
'{!s:<5.5}'.format(4257647474747)
Run Code Online (Sandbox Code Playgroud)