格式化字符串语法

2024-10-02 12:32:32 发布

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

我用python编写了以下代码:

"{0}.currentTime += 1;".format(hairSyst)

其中hairSyst是前面定义的字符串。我不明白为什么我得到一个语法错误。我的目标是在maya中设置一个表达式,表达式有点长,我将整个内容粘贴在下面,也许您可以建议一个更好的方法来实现它。在

^{pr2}$

Tags: 方法字符串代码format内容目标定义表达式
2条回答

最好是一个format字符串:

expr = """if ({0}.autoOverlap == 1){{
          {1}.currentTime += 1;
          {2}.currentTime += 1;
          float $refresh_tx = {3}.translateX;
          float $refresh_ty = {3}.translateY;
          float $refresh_tz = {3}.translateZ;
          float $refresh_rx = {3}.rotateX;
          float $refresh_ry = {3}.rotateY;
          float $refresh_rz = {3}.rotateZ;
          }}else if({0}.autoOverlap == 0){{"
          {1}.currentTime = 1;
          {2}.currentTime = 1;
          }}""".format(firstControl.getName(), hairSyst, nucleus, cube)

注意使用"""三重引号而不是"单引号来格式化多行字符串。在

编辑:

如果原始字符串包含{ },我们必须按照documentation对它们进行转义:

6.1.3. Format String Syntax

The str.format() method and the Formatter class share the same syntax for format strings (although in the case of Formatter, subclasses can define their own format string syntax).

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

你必须连接这些字符串。现在,eval()看到您传递了13个字符串,但是eval()只接受一个字符串。所以就这样做吧:

expr = ("if ({0}.autoOverlap == 1){ ".format(firstControl.getName()) + 
     "{0}.currentTime += 1; ".format(hairSyst) + 
     "{0}.currentTime += 1; ".format(nucleus) + 
     "float $refresh_tx = {0}.translateX; ".format(cube) + 
     "float $refresh_ty = {0}.translateY; ".format(cube) + 
     "float $refresh_tz = {0}.translateZ; ".format(cube) + 
     "float $refresh_rx = {0}.rotateX; ".format(cube) + 
     "float $refresh_ry = {0}.rotateY; ".format(cube) + 
     "float $refresh_rz = {0}.rotateZ; ".format(cube) + 
     "}else if({0}.autoOverlap == 0){ ".format(firstControl.getName()) + 
     "{0}.currentTime = 1; ".format(hairSyst) + 
     "{0}.currentTime = 1; ".format(nucleus) + 
     "}"
)

我在每个字符串后面添加了空格,以确保它们不会碰到对方。在

相关问题 更多 >

    热门问题