3
$\begingroup$

Consider an example list with mixed element types, e.g.:

list = { 1.234 , a[2] , {"Abc" , 4/5} , "acb" };

I would like to have a function that finds the position of a string, without regard to upper or lower characters, e.g.:

findPosition[list,"abc"]

{{3,1}}

Is there a function like that in Mathematica? Or maybe one can implement it with efficient performance?

EDIT:

My current workaround is:

findPosition[list_,str_]:=Position[list/.x_String:>ToLowerCase[x],ToLowerCase[str]]
$\endgroup$
2
$\begingroup$

Recall that StringMatchQ[] has the IgnoreCase option:

Position[{1.234, a[2], {"Abc", 4/5}, "acb"},
         s_String /; StringMatchQ[s, "abc", IgnoreCase -> True]]
   {{3, 1}}
$\endgroup$
  • 1
    $\begingroup$ Decided to go with this answer after all, since it is minimal, as all it does is a query -- no operations on the data. $\endgroup$ – Kagaratsch Mar 31 at 3:11
3
$\begingroup$
Position[list, s_String /; ToLowerCase[s] == "abc"]

{{3, 1}}

or

Position[list, s_String?(EqualTo["abc"]@*ToLowerCase)]
$\endgroup$
  • $\begingroup$ I like how this does not need to make substitutions in list itself to search it! $\endgroup$ – Kagaratsch Mar 30 at 21:24
  • 2
    $\begingroup$ Position[ToLowerCase[list], "abc"] also works. $\endgroup$ – C. E. Mar 30 at 22:17
  • $\begingroup$ The rationale behind using a _String pattern is to pre-filter with a very inexpensive test: This ensures that only few expressions are actually fed to ToLowerCase. $\endgroup$ – Henrik Schumacher Mar 31 at 7:19
3
$\begingroup$

Note that ToLowerCase does not evaluate if the input is not a string, but it is Listable, so it will thread over your list:

list = {1.234, a[2], {"Abc", 4/5}, "acb"};
ToLowerCase[list]

(* Out: {ToLowerCase[1.234], ToLowerCase[a[2]], {"abc", ToLowerCase[4/5]}, "acb"} *)

That should not bother you though; it certainly does not bother Position:

Position[ToLowerCase[list], "abc"]
(* Out: {{3, 1}} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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