Skip to content
Advertisement

How do I replace multiple blank spaces occuring in a text file with a single space in python

with open("test.234.txt", 'r') as f:
    a=f.read()

with open("test234(double space replaced by singleones)" ,"w+") as f:
    for i in range(len(a)-1):
        if( a[i]+a[i+1] == "  "):
            a[i].replace(a[i],"")
            a[i+1].replace(a[i+1]," ")
            f.write(a[i]+a[i+1])

        else:
            f.write(a[i])
            

Advertisement

Answer

Split string by default splits string at spaces and ignores multiple consecutive spaces:

with open("test.234.txt", 'r') as f:
    a=f.read()

with open("test234(double space replaced by singleones)" ,"w+") as f:
    for i in range(len(a)-1):
        f.write(' '.join(a[i].split()))
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement