【问题标题】:Syntax error when concatenating a string in Cython在 Cython 中连接字符串时出现语法错误
【发布时间】:2015-01-22 17:04:16
【问题描述】:

我在 cdef 类(Cython 语言)中有以下代码:

def toString(self):
    res = "lut= " + str(self._mm_np[0].lut) +
        "n1= "  + str(self._mm_np[0].n1) +
        "nlay= "+ str(self._mm_np[0].nlay) +
        "n3= "  + str(self._mm_np[0].n3)
    return res

当我尝试编译包含此代码的 cython 文件时,我收到以下语法错误: “预期的标识符或文字”指向字符串连接中的第一个“+”。

我尝试使用'\'而不是'+'但没有成功.. 在 Pyhton/Cython 中连接字符串的正确方法是什么? 谢谢!

【问题讨论】:

    标签: python cython


    【解决方案1】:

    您缺少续行运算符\

    def toString(self):
        res = "lut= " + str(self._mm_np[0].lut) + \
        "n1= "  + str(self._mm_np[0].n1) + \
        "nlay= "+ str(self._mm_np[0].nlay) + \
        "n3= "  + str(self._mm_np[0].n3)
        return res
    

    ...但你真的不应该那样做。这被认为是糟糕的风格。

    探索使用.format 方法代替字符串;它将为该字符串提供位置参数,因此您不必 进行连接。

    def toString(self): 
        return "lut={} n1={} nlay={} n3={}".format(
                    str(self._mm_np[0].lut),
                    str(self._mm_np[0].n1),
                    str(self._mm_np[0].nlay),
                    str(self._mm_np[0].n3))
    

    【讨论】:

    • 谢谢,很有帮助。
    猜你喜欢
    • 2019-04-03
    • 2020-10-11
    • 2012-07-26
    • 1970-01-01
    • 2019-11-03
    • 2011-12-16
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    相关资源
    最近更新 更多