0
$\begingroup$

Sorry for the bad title..Didn't know how to describe this, feel free to change it to be more specific.

I have a list in this form:

list = {"a(0)", "a(1)", "a(2)"}

Now I want the positions of all a* in the list. At first I thought this is easily done with the Position-function, but then I had some difficulties:

Position[list, "a"]

Thought this would work, but somehow I'm missing something. So..how to implement the * to give me all a's regardless of the following characters?

$\endgroup$
3
  • 2
    $\begingroup$ StringPosition[list, "a"]? $\endgroup$
    – Apple
    Jul 10, 2014 at 11:22
  • $\begingroup$ omg..of course! I forgot to transform my list into a string :).. $\endgroup$
    – holistic
    Jul 10, 2014 at 11:30
  • $\begingroup$ No need to transform anything. $\endgroup$
    – Kuba
    Jul 10, 2014 at 11:40

2 Answers 2

2
$\begingroup$

If you really want to use Position :)...

Position[list, s_String?(! StringFreeQ[#, "a"] &)]
{{1}, {2}, {3}}
$\endgroup$
4
  • $\begingroup$ This is nice and I get the correct results. But there is a warning message which I don't understand: StringFreeQ::strse: "String or list of strings expected at position 1 in \!(StringFreeQ[List, \"a\"]). " $\endgroup$
    – holistic
    Jul 10, 2014 at 11:58
  • 1
    $\begingroup$ Try Position[list, s_String?(! StringFreeQ[#, "a"] &)]. $\endgroup$
    – Kuba
    Jul 10, 2014 at 12:02
  • $\begingroup$ works fine now! Can you explain why what the problem was maybe? Want to understand it :) $\endgroup$
    – holistic
    Jul 10, 2014 at 12:04
  • 1
    $\begingroup$ @holistic Position is scanning everything, Heads too, that's why we had to constrain the pattern. You could also do Position[list, s_?(! StringFreeQ[#, "a"] &), Heads->False] but the method with String is more safe in case of nonstrigs in the list. $\endgroup$
    – Kuba
    Jul 10, 2014 at 12:11
1
$\begingroup$
list = {"a(0)", "a(1)", "a(2)", "b(42)"}

You can get the elements that match like so:

els = Select[list, StringMatchQ[#, "a" ~~ ___] &]

(*
{"a(0)", "a(1)", "a(2)"}
*)

If you want their positions, you can map Position over this list:

Position[list, #] & /@ els

(*
{{{1}}, {{2}}, {{3}}}
*)
$\endgroup$

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