4
$\begingroup$

This is a rather basic question but as I am new to programming, I have been stuck on it for a little while. I am trying to add strings to the beginning and end of every element in a list (each element in the list is a string).

I know to use the StringJoin or <> function to join strings individually, e.g.: "what I want to add"<>"original string"<>"what I want to add". However, I am having some trouble applying this broadly to each element in a list. I think I am supposed to use the Map or /@ function, but am simply lost at how to apply it correctly.

Here is an example:

exampleList={"apple","pear","banana","orange"}

In the beginning of each element, I want to add the string: "Is this fruit a " and in the end: "?" so that the changed list would yield:

exampleList={"Is this fruit a apple?", "Is this fruit a pear?", "Is this fruit a banana?", "Is this fruit a orange?"}

Any help would be greatly appreciated

$\endgroup$
3
  • 6
    $\begingroup$ Try StringTemplate["Is this fruit a ``?"] /@ {"apple", "pear", "banana", "orange"}. $\endgroup$ Apr 23, 2017 at 17:48
  • 3
    $\begingroup$ or, StringForm["Is this fruit a ``?", #] & /@{"apple","pear","banana","orange"} for version 9 and earlier versions. $\endgroup$
    – kglr
    Apr 23, 2017 at 17:54
  • $\begingroup$ @kglr that worked like a charm, thank you! $\endgroup$ Apr 23, 2017 at 19:52

3 Answers 3

5
$\begingroup$

Here is a way to do it producing better English:

Map[
 StringTemplate["Is this fruit `1` `2`?"] @@ 
   If[MemberQ[Characters["aeiou"], 
     StringTake[#, 1]], {"an", #}, {"a", #}] &, 
   {"apple", "pear", "banana", "orange"}]

(* {"Is this fruit an apple?", "Is this fruit a pear?", 
    "Is this fruit a banana?", "Is this fruit an orange?"} *)
$\endgroup$
2
$\begingroup$
ToString /@ StringForm["Is this fruit a ``?", #] & /@{"apple","pear","banana","orange"}

or

ToString /@ (Row[{"Is this fruit a ", "?"}, #] & /@ {"apple", "pear", "banana", "orange"})

to get

{"Is this fruit a apple?", "Is this fruit a pear?", "Is this fruit a banana?", "Is this fruit a orange?"}

$\endgroup$
2
  • $\begingroup$ ToString[] will be needed if the OP wants actual strings. $\endgroup$ Apr 23, 2017 at 21:19
  • $\begingroup$ Thank you @J.M. I updated with your suggestion. $\endgroup$
    – kglr
    Apr 23, 2017 at 21:23
0
$\begingroup$
("is this " <> (StringMatchQ[#, Alternatives @@ Characters@"aeiou" ~~ __] /. {True ->"an "
<> #, False -> "a " <> #}) <> "?") & /@ exampleList

(*{"is this an apple?", "is this a pear?", "is this a banana?", "is this an orange?"}*)
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.