9

I recently came across the following piece of code. It doesn't look valid because of the single instance of triple quotes but seems to work fine. Can anyone explain what's going on here?

return ("Validation failed(%s): cannot calculate length "
        "of %s.""" % (self.name, value))`

4 Answers 4

9

All of the strings are concatenated first.

"" is an empty string.

The substitutions are then made.

Sign up to request clarification or add additional context in comments.

2 Comments

Surely nobody would ever write such confusing code. I reject the premise of the question!
So no white space is required between the concatenated strings and the final empty string, repeated in several places in the code (I can post a link for the doubting Felix), is just poor coding.
4

This is Python's string literal concatenation - essentially, string literals appearing directly next to each other are parsed as a single string:

>>> 'foo' 'bar'
'foobar'

In your example, you have three string literals in a row (the last is "", the empty string) being concatenated this way, rather than a single multi-line literal that is terminated but not started with triple quotes.

Comments

1

When you use String on multiple line you can add " to make a single line output as string are concatenate first. You can read the line as :

return ("Validation failed(%s): cannot calculate length " //1st line
    "of %s." //2nd line
    "" % (self.name, value)) //3rd line (empty)

Comments

0

If you can modify the code, note that the % syntax for formatting strings is becoming outdated. You should use str.format() if your version of Python supports it:

return "Validation failed({0}): cannot calculate length of {1}.".format(self.name, value)

If it needs to span multiple lines, use:

return ("Validation failed({0}): " +
        "cannot calculate length of {1}.".format(self.name, value))

1 Comment

This should be a comment, since it doesn't actually answer the question - also, no need for the +, because of exactly the same string literal concatenation in the original code.

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.