removing characters before writing to file

John Zenger john_zenger at yahoo.com
Thu Feb 9 07:27:10 EST 2006


As mentioned in the thread, it makes sense to build the desired output 
you want from the tuple, rather than converting the tuple to a string 
and then doing replace operations on the string.

If you do want to go the replace route, you don't need the power of 
regex substitutions for what you are interested in.  Just try the 
replace method:

 >>> foo = "('sometext1', 1421248118, 1, 'P ')"
 >>> foo.replace("\'", "").replace("(", "").replace(")", "")
'sometext1, 1421248118, 1, P '

or, more elegantly:

 >>> "".join([x for x in foo if x not in ['(',')','\''] ])
'sometext1, 1421248118, 1, P '

However, all of these replace-based solutions are bad because they will 
not only replace the apostrophes and parentheses between the strings, 
but also within them; what if "sometext1" is actually "John's Text?" 
You are much better off building your desired output from the actual 
tuple data yourself.

eight02645999 at yahoo.com wrote:
> hi
> i have some output that returns a lines of tuples eg
> 
> ('sometext1', 1421248118, 1, 'P ')
> ('sometext2', 1421248338, 2, 'S ')
> and so on
> ....
> 
> I tried this
> re.sub(r" '() ",'',str(output)) but it only get rid of the ' and not
> the braces. I need to write the output to a file such that
> 
> sometext1, 1421248118, 1, P
> sometext2, 1421248338, 2, S
> 
> I also tried escaping , re.sub(r" '\(\) ",'',str(output)) but also did
> not work
> How can i get rid of the braces before writing to file? thanks
> 



More information about the Python-list mailing list