how to remove form feed from string in python

Viewed 698

I have a text file that contains the following:

'\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c'

As you see it's all form feed characters, which I want to have removed.

I have tried various solutions but for some reason they don't seem to work. For example, what I have tried is to remove the left '\x0c, the right \x0c', and all the other \x0c, but the output remains the same. The code is use:

import re
import string

with open('AF-40-A-00020539.txt', "r", encoding="ascii") as input_file:
    input_content = input_file.read()
    print(
        input_content.lstrip('\'\x0c')\
            .rstrip('\x0c\'')\
            .strip('\x0c')
            .replace('\x0c', '')
    )

After executing this, I get this as output \x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c' so not what I would expect.

What is the reason for this? How can I remove the form feed characters?

UPDATE, thanks to joao's answer: \xHH, where HH are two hex digits, is a recognised escape sequence to write ASCII characters using their corresponding hex value, just like \n is for a newline.

The .replace('\x0c', '') did not work because in this string literal \xOc got escaped, whereas in the text file, it was just copied as plain text.

3 Answers

There's an ambiguity here: when you say the file contains \x0c, is that a single character in the file, displayed with the escape sequence that represents the hex value 0x0c ? Or is it really a 4-character string ? You should try to determine that with a binary editor, or the len() function.

I suspect the 2nd case, because you say that you get \x0c as output. If it were the 1st case, you'd see ^L, or a blank line, or some gibberish indicating a non-printable character.

If it's a single character, then

s = s.replace('\x0c', '')

will remove them. If they're really 4 characters, then

s = s.replace('\\x0c', '')

should work. Note the extra backslash \ that turns an escape sequence into a 4-character string.

I'm not 100% sure but try this in .replace:

line.replace('\x0C', '')

Let me know :)

You can use re.sub():

import re
string = "Hello, '\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c'World!"
print(re.sub(r"'(\x0c)+'", '', string))

Output:

Hello, World!
Related