Assume we have a list
list = {"a", "b", "c", "d", "e", "f"}
Then use this code:
StringRiffle[list,"*"]
But "*a*b*c*d*e*f*"
is expected.So we should
"*" <> StringRiffle[list,"*"] <> "*"
Have a terse method do this?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityStringRiffle
can also take strings to prepend and append to the result if you supply three delimiters instead of one. It's not that much terser though:
StringRiffle[list, {"*", "*", "*"}]
Of course you could remove the duplication of the strings with
StringRiffle[list, ConstantArray["*", 3]]
if you like.
For the sake of completeness, the order of the three strings in the list is {prefix, infix, suffix}
, e.g.
StringRiffle[list, {"<", "*", ">"}]
(* "<a*b*c*d*e*f>" *)
Alternatively, if you always want to insert some string before/after every character (that is, if the strings in list
will never contain two or more characters), you can also use StringReplace
:
StringReplace["abcdef", "" -> "*"]
(* "*a*b*c*d*e*f*" *)
StringReplace[StringJoin@list,RegularExpression["\\B|\\b"]->"*"]
$\endgroup$
StringReplace["adefgh12c34", "" -> "*"]
but of course a lot less flexible since StringRiffle
's first list may contain strings that are longer than a single character. I'll add this though if it's useful to you.
$\endgroup$
Mar 23, 2016 at 15:48