5月份的填充数量/版本

2024-04-27 01:05:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个代码来做一个数字/版本填充,但当我试图在互联网上搜索,我只能找到一个MEL的例子,在其中它工作,但它对我来说没有意义(很可能我不明白它是如何工作的)

$padding = 3;
$num = 5;
string $pad = `python ("'%0"+$padding+"d' % "+$num)`;
// Results is: 005

但是,当我尝试将其转换为Python样式时,我得到了以下结果:

^{pr2}$

甚至当我试图重新排列代码时,结果要么是错误的(如您所见,完全错误)要么是Maya错误,如TypeError: cannot concatenate 'str' and 'int' objects

有什么建议吗?在


Tags: 代码版本stringis错误样式互联网数字
1条回答
网友
1楼 · 发布于 2024-04-27 01:05:26
padding = '3'
num = '5'
pad = ("%%0%si" % padding) % int(num)
print pad # prints '005'

工作原理:

字符串处理后,使用%%将%%转义到%:

^{pr2}$

工作原理:(第二次尝试;)

当我们处理字符串时,“%”有特殊的含义

"%s" Replaced with a string
"%i" Replaced with an integer
"%%" means I am an "%", kinda like \n is newline and \\ is \

可以通过在%x之间输入数字来修改%x

"%10s" means a string padded to 10 with spaces
"%010i" means an integer padded to 10 with zeros

我们想要的是整数1,因为数字零部分必须来自一个变量,我们必须进行两个字符串处理步骤,因此我们在第一轮字符串处理中使用%%->;%技巧,得到%03i'

这里我用括号把东西按逻辑组合在一起,在实际代码中当然没有括号:)

"(%%)0(%s)i" % num

%% => %
"%s" % num => '3'

(%)0(3)i
%03i

相关问题 更多 >