0

I have the following code inside a cdef class (Cython language):

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

when I try to compile the cython file containing this code I get the following syntax error: "Expected an identifier or literal" that pointing on the spot with the first '+' in string concatenation.

I have tried to use '\' instead of '+' with no success.. What is the right way to concatenate strings in Pyhton/Cython? Thank you!

1 Answer 1

1

You're missing the line continuation operator \:

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

...but you really shouldn't do that. It's considered poor style.

Explore the usage of the .format method for strings instead; it will provide positional arguments to that string so you don't have to concatenate.

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.