Comments
Michael Chermside
mcherm at mcherm.com
Thu Apr 3 09:18:32 EST 2003
Carsten Gaebler wrote:
> But multi-line strings are evil, too. At least when they occur in an
> indented block and leading whitespace is not allowed in the string
> your're building
Greg Ewing replied:
> Last time I pondered this issue, I decided that the
> correct way to fix this would be to have a statement
> like
>
> string my_string:
> | The string can contain any characters and
> |have multiple lines and leading whitespace,
> |and its indentation level is made clear by
> |the leading | characters.
>
> Teaching the tokenizer to understand this could
> be an interesting exercise, however...
Would this work for you?
myString = stripLeading("""
| The string can contain any characters and
|have multiple lines and leading whitespace,
|and its indentation level is made clear by
|the leading | characters.""")
If so, it has three advantages. First of all, no need for a
type declaration (been doing too much C lately?). Secondly,
it is clear where the construct ends (thus being a bit more
readable if your string ended in a newline). Secondly, it
can be implemented without having to teach the tokenizer
anything.
import re
def stripLeading(s):
prefix = re.match('\n[ \t]*.', s).group()
return myString.replace(prefix, '\n')[1:]
I'm not sure this is the single BEST way to write indented
multi-line strings (personally I'd avoid the line of |'s),
but if you like it, it's pretty darn easy to get.
-- Michael Chermside
More information about the Python-list
mailing list