I am looking for a way to output a character
a number of times using format. Is this possible? Can someone fill
in the _?_
's, so that the example works?
(let ((n 3))
(format nil "_?_" _?_ #\* _?_ ))
should return
=> "***"
I am looking for a way to output a character
a number of times using format. Is this possible? Can someone fill
in the _?_
's, so that the example works?
(let ((n 3))
(format nil "_?_" _?_ #\* _?_ ))
should return
=> "***"
Like the answer of Lars, but we write the character wih
~C
, instead of using the printer with~A
:Writing a character with something like
write-char
is a simpler operation than printing a Lisp object. The printer has a lot of context to observe and has to find the right way to print the object. OTOH, something likeWRITE-CHAR
just writes a single character to a stream.If you use the
~A
directive, you can get this in exactly the form that you suggested, i.e.,with three format arguments. However, if you use
~<
, you can actually do this with just two format arguments. If you don't need this string inside of some other string that's already being generated byformat
, you could also just make the string usingmake-string
.Using Tilde A (~A)
You could print the character and specify a minimum width and the same character as the padding character. E.g., using
~v,,,vA
and two arguments, you can ensure that some number of characters is printed, and what the padding character is.This uses the full form of
~A
:as well as
v
:Using Tilde Less Than (~<)
There's also a less commonly used format directive, tilde less than, that's used for justification. it takes a format string and makes s
We can (ab)use this by passing an empty format string and just specifying the width and the padding character:
Just make a string
Of course, unless you need this special string inside of some other string that you're already formatting, you should do what wvxvw suggested, and just use
make-string
:Other alternatives
format
is very flexible, and as this and other answers are pointing out, there are lots of ways to do this. I've tried to stick to ones that should do this in one pass and not do explicit iterations, but this can be done withformat
iterations, too, as Lars Brinkhoff and wvxvw have pointed out.Or elaborating a bit on Joshua Taylor's answer:
Would be one way of doing this. Don't be confused by the asterisks in the
format
directive, they are control characters, not characters being printed.In terms of efficiency, however, this:
would be a preferred way to achieve the same effect.
It's nice to see so many solutions: ~A, ~<, and ~{ so far.
The ~@{ iteration construct provides a concise solution: