F
F
fantom00052015-12-19 02:37:09
Python
fantom0005, 2015-12-19 02:37:09

How to replace a substring in Python while keeping part of that string?

The essence of the question is this, you need in the input line like

string = "cos(90) + cos(170) + sin( 80)" #могут быть и другие математические функции

make these changes:
out_string = "cos(degres(90)) +  cos(degres(170)) + sin(degres( 80))"

I wrote such a regular expression:
(cos *\( *(?P<degres>[\d]+) *\))
how can I replace the cosines with it, and leave the numbers?
and another question: how to make it change both sines and tangents?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nirvimel, 2015-12-19
@nirvimel

import re
string = "(cos(0) + sin(180)) * tan(45.0) + not_a_tan(1)"
print re.sub(r'\b(cos|sin|tan)\s*\(\s*(\d+(?:\.\d+)?)\s*\)', r'\1(degres(\2))', string)

Handles integer and fractional numbers correctly.
Does not respond to other functions ending in cos, sin, or tan.
At the same time corrects the spacing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question