Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question

closed as off-topic by Öskå, Michael E2, whuber, m_goldberg, bobthechemist Jul 10 at 14:43

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – Öskå, Michael E2, whuber, m_goldberg, bobthechemist
If this question can be reworded to fit the rules in the help center, please edit the question.

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

3 Answers 3

up vote 1 down vote accepted

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

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

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

share|improve this answer
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}}}
*)
share|improve this answer

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