Python Forum

Full Version: Replace characters from file in Python 2.7
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello

I can't replace more strings from file, i use two ways:
  • function lambda
  • expr regulier

#! /bin/python
import re
import sys
import fileinput
import os
stripped = lambda s: "".join(i for i in s if 31 < ord(i) < 127)
#en dur ça marche
print(stripped('\xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah'))
 
for line in fileinput.input('fic.txt'):
    #with exrp regu
    line1 = re.sub(r'[^\x00-\x7f]', r'', line.rstrip())
    print(line1)
    ####################
    #with lambda
    print(stripped(line.rstrip()))
Output:
>cat fic.txt \xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah
Thanks for help
What exactly are you trying to do? I'm not sure what result you are trying to get.
Hello,
I use three methods to replace "\xe2\x80\x9c and" "\xe2\x80\x9d" :
The first give me a good result
stripped = lambda s: "".join(i for i in s if 31 < ord(i) < 127)
#en dur ça marche
print(stripped('\xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah'))
Output:
http://www.google.com blah blah#%#@$^blah
but the others not ok
for line in fileinput.input('fic.txt'):
    #with exrp regu
    line1 = re.sub(r'[^\x00-\x7f]', r'', line.rstrip())
    print(line1)
    ####################
    #with lambda
    print(stripped(line.rstrip()))
Output:
\xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah \xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah
I thank it's clear now.

Thanks for help