Search code examples
pythonpython-3.xregexfor-looppython-re

Inserting Commas before float numbers python


I am new to python. I have a string which looks like below:

a= "1.1 Introduction 1.2 Inverse of a Non-Singular 1.3 Elementary Transformations  1.4 Applications 1.5 Applications of Matrices"

I want the comma to be inserted before number in the String.

Code I tried:

a= "1.1 Introduction 1.2 Inverse of a Non-Singular 1.3 Elementary Transformations  1.4 Applications 1.5 Applications of Matrices"

b = ""
for i in a:
   print(i)
   try: 
       temp = int(i)
       b = b+ ","+ temp
   except:
       b = b + i

But it's wrong. Please help me with some solutions.

Required Output:

"1.1 Introduction, 1.2 Inverse of a Non-Singular, 1.3 Elementary Transformations,  1.4 Applications, 1.5 Applications of Matrices"

Solution

  • This might be helpful:

    import re
    
    a= "10.1 Introduction 10.2 Inverse of a Non-Singular 1.3 Elementary Transformations  1.4 Applications 1.5 Applications of Matrices"
    
    re.sub(r"\s+(\d+\.\d+)", r", \1", a)