Welcome to MMA SE! So, essentially the problem here is that line breaks don't count for anything inside expressions—only between expressions. So,
a = 4
b = 5
is fine, and is interpreted as two separate inputs;
a = (Echo[3]
5)
is not interpreted as "do Echo
, then 5
". Within an expression, you need to use ;
to separate sequentially-evaluated parts. Otherwise, line breaks, like spaces, are interpreted as Times
!
That's relevant here because in the lines
For[i = StringLength[word], i > 0, i--,
AppendTo[wordchar, StringPart[word, i]
]
]
wordchar
you're essentially multiplying the output of the For
loop, which is Null
, by the list wordchar
. Since multiplication is threaded over lists automatically, you get Null
multiplying every string in the list. Check out butterfly["abcdef"] // FullForm
to see the Times
explicitly!
So, modifying it to
butterfly[word_] :=
Module[{wordchar = {}},
For[i = StringLength[word], i > 0, i--,
AppendTo[wordchar, StringPart[word, i]
]
];
wordchar
]
should fix it!
Note, however, that For
loops are very "non-Mathematica-l"! Generally, you'll want to use Table
(or maybe Array
, or Sow
and Reap
for "AppendTo
—like functionality") to build lists, not For
and AppendTo
—and it'll typically be easier than setting up a For
-loop, since the iterated-over variable already behaves the way you want.
Your code also sets the global variable i
; "good practice" would be to put it in the Module
as well (if you were going to use it)!
StringTake[word, {-1, 1, -1}]
$\endgroup$