# Convert Python math expression form (Sin and Cos) to Python math expression?

I have a really big symbolic output from Python, and it contains Sin and Cos. Now I want to solve it using Mathematica, but the sin and cos are written like sin(x) cos(x). How can I get them like Sin[x] Cos[x] using Mathematica?

• While @lowriniak's solution is certainly useful, you might also consider loading the expression into a text editor, and using ReplaceAll (ctrl+h). Dec 5, 2016 at 16:20

If this is the only problem then:

ToExpression["sin(x) cos(x)", TraditionalForm]

Cos[x] Sin[x]


here is a less hacky solution, the assumption is that there are no notmatching () escaped in strings or something:

FixedPoint[
StringReplace[
h : LetterCharacter .. ~~ "(" ~~ Shortest[x__] ~~ ")" /;
StringCount[x, "("] == StringCount[x, ")"] :>
Capitalize[h] <> "[" <> x <> "]"
],
"sin(sin(y))+cos(zxc)"
]


"Sin[Sin[y]]+Cos[zxc]"

Now, you can ToExpression if you want.

As george2079 noticed an operator form of StringReplace is new in 10.4 so for older versions one may need to use StringReplace[#, pattern]& instead of StringReplace[pattern].

Capitalize is new in 10.1 so for older versions the replacement would be something like: StringReplacePart[#, ToUpperCase@StringTake[#, 1], {1, 1}] &

• Very interesting. What would be a less trivial example? Or does it only cover the simple (x)[x], etc. transformations? Dec 5, 2016 at 20:42
• This is a hack that only works when the syntax is simple. But it is really convenient. I use this all the time to transfer expressions. String patterns can't deal with bracket matching in general. +1 Dec 6, 2016 at 10:52
• Seems good. But my first comment wasn't a criticism. Dec 7, 2016 at 11:51
• note the operator form of StringReplace is new in 10.4 or so. Need to do StringReplace[#, h: .... ]& for older versions. Dec 7, 2016 at 17:54
• @george2079 thanks, I've added two notes for older versions users.
– Kuba
Dec 7, 2016 at 18:09

You could import it as a string then use

StringReplace[
string,
{
"sin("~~Shortest[x__]~~")" :> "Sin["<>x<>"]",
"cos("~~Shortest[x__]~~")" :> "Cos["<>x<>"]"
}
]


You would then use ToExpression to turn it into code input.

• What about "sin(sin(y))"? This is why I prefer the TraditionalForm solution that Kuba showed, even though it is an ugly hack. You could replace all ( by [, but that will replace grouping parens too. Regular expressions are not capable of dealing with recursive tasks like bracket matching. A proper solution would require a full-blown parser. The closest ready-made thing we have to that is TraditionalForm parsing. Dec 6, 2016 at 10:54
• Maybe use Anton's parser? github.com/antononcube/MathematicaForPrediction/blob/master/… Dec 6, 2016 at 10:58