yhussain
yhussain

Reputation: 308

Python Search & Replace With Regex

I am trying to replace every occurrence of a Regex expression in a file using Python with this code:

import re

def cleanString(string):
    string = string.replace(" ", "_")
    string = string.replace('_"', "")
    string = string.replace('"', '')
    return string

test = open('test.t.txt', "w+")
test = re.sub(r':([\"])(?:(?=(\\?))\2.)*?\1', cleanString(r':([\"])(?:(?=(\\?))\2.)*?\1'), test)

However, when I run the script I am getting the following error:

Traceback (most recent call last):
  File "C:/Python27/test.py", line 10, in <module>
    test = re.sub(r':([\"])(?:(?=(\\?))\2.)*?\1', cleanString(r':([\"])(?:(?=(\\?))\2.)*?\1'), test)
  File "C:\Python27\lib\re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer

I think it is reading the file incorrectly but I'm not sure what the actual issue is here

Upvotes: 0

Views: 377

Answers (1)

Alexandru Chirila
Alexandru Chirila

Reputation: 2352

Your cleanString function is not returning anything. Ergo the "NoneType" error.

You probably want to do something like:

def cleanString(string):
    string = string.replace(" ", "_")
    string = string.replace('_"', "")
    string = string.replace('"', '')
    return string

Upvotes: 1

Related Questions