How to print a string representation of an object in D?
I would like to do something equivalent to Python repr:
>>> x = "a\nb\nc"
>>> print x
a
b
c
>>> repr(x)
"'a\\nb\\nc'"
>>> print repr(x)
'a\nb\nc'
How can I do this in D? Is there a format directive similar to Python %r?
EDIT: I want to be able to print strings in their escaped form for debugging purposes (I just started learning D and I am writing dumb text processing functions).
D , escape-, , ( , Python ). , , ( - ).
toString(), .
: D. : , . Unicode , .
import std.stdio;
import std.exception;
void main() {
writeln(repr("This\nis\n\t*My\v Test"));
}
string repr(string s) {
char[] p;
for (size_t i; i < s.length; i++)
{
switch(s[i]) {
case '\'':
case '\"':
case '\?':
case '\\':
p ~= "\\";
p ~= s[i];
break;
case '\a':
p ~= "\\a";
break;
case '\b':
p ~= "\\b";
break;
case '\f':
p ~= "\\f";
break;
case '\n':
p ~= "\\n";
break;
case '\r':
p ~= "\\r";
break;
case '\t':
p ~= "\\t";
break;
case '\v':
p ~= "\\v";
break;
default:
p ~= s[i];
break;
}
}
return assumeUnique(p);
}
, escape- . , (, ), .
If you control the source, you can use raw strings . Just put rin front of your line.
"a\tb" => "a b"
r"a\tb" => "a\tb"