# Positions of a string in a list [duplicate]

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?

-

## marked as duplicate by Mr.Wizard♦Jul 17 at 8:16

StringPosition[list, "a"]？ –  Apple Jul 10 '14 at 11:22
omg..of course! I forgot to transform my list into a string :).. –  holistic Jul 10 '14 at 11:30
No need to transform anything. –  Kuba Jul 10 '14 at 11:40

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

Position[list, s_String?(! StringFreeQ[#, "a"] &)]

{{1}, {2}, {3}}

-
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\"]). " –  holistic Jul 10 '14 at 11:58
Try Position[list, s_String?(! StringFreeQ[#, "a"] &)]. –  Kuba Jul 10 '14 at 12:02
works fine now! Can you explain why what the problem was maybe? Want to understand it :) –  holistic Jul 10 '14 at 12:04
@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. –  Kuba Jul 10 '14 at 12:11
Thank you very much :) –  holistic Jul 10 '14 at 12:34
list = {"a(0)", "a(1)", "a(2)"};
StringPosition[list, "a"]


{{{1, 1}}, {{1, 1}}, {{1, 1}}}

-
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}}}
*)

-