Search code examples
pythonstringduplicates

How to remove duplicates of a single character in string python?


I have a string like this:

$$\\int_{-\\infty}^{\\infty}\\int_{-\\infty}^{\\infty}{{e^{(x+y)}}^2}dxdy$$

But what i want is:

$$\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}{{e^{(x+y)}}^2}dxdy$$

Is there a way to do that?


Solution

  • First of all, if this is a string literal, then it will properly escape the slash, and you will get the result you want:

    print("$$\\int_{-\\infty}^{\\infty}\\int_{-\\infty}^{\\infty}{{e^{(x+y)}}^2}dxdy$$")
    

    Otherwise, you could just replace the characters with one of it:

    string = "$$\\int_{-\\infty}^{\\infty}\\int_{-\\infty}^{\\infty}{{e^{(x+y)}}^2}dxdy$$"
    
    string = string.replace(r'\\', '\\')