4
$\begingroup$

I can't seem to figure out how to use Position function correctly. For example:

Position[{"aaa", "bbb", "ccc", "abc", "bbc", "cca"}, "cc"]

I would like the function to return {3, 6} as these are the only two positions in the list that contain the string "cc". I'm sure this probably has something to do with patterns, but can't seem to figure it out.

$\endgroup$
5
$\begingroup$

One way might be

 str = {"aaa", "bbb", "ccc", "abc", "bbc", "cca"}
 Position[StringContainsQ[str, "cc"], True]

Mathematica graphics

| improve this answer | |
$\endgroup$
5
$\begingroup$

Position has some unusual defaults. As ref/Position says

The default level specification for Position is {0,Infinity}, with Heads->True.

So it is a little tricky to use StringContainsQ directly in a pattern given to Position, but it can be done.

Position[
  {"aaa", "bbb", "ccc", "abc", "bbc", "cca"},
  _?(StringContainsQ["cc"]), 
  {1}, 
  Heads -> False]

{{3}, {6}}

| improve this answer | |
$\endgroup$

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