5
$\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$

3 Answers 3

3
$\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
  • 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, 2019 at 3:11
4
$\begingroup$
Position[list, s_String /; ToLowerCase[s] == "abc"]

{{3, 1}}

or

Position[list, s_String?(EqualTo["abc"]@*ToLowerCase)]
$\endgroup$
3
  • $\begingroup$ I like how this does not need to make substitutions in list itself to search it! $\endgroup$
    – Kagaratsch
    Mar 30, 2019 at 21:24
  • 2
    $\begingroup$ Position[ToLowerCase[list], "abc"] also works. $\endgroup$
    – C. E.
    Mar 30, 2019 at 22:17
  • 1
    $\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$ Mar 31, 2019 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 and acknowledge you have read our privacy policy.

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