Skip to content
Advertisement

Replacing ‘x..’ litteral string in Python

I have directories that contains ‘x..’ characters such as ‘x00’ :

JavaScript

and I want to rename them without these, since when I copy those files to windows they become unusable. So my python script is going through those directories and detecting the problematic characters the following way:

JavaScript

First I thought I could get rid of this problem by using the re module in python:

JavaScript

But this didn’t work. Is there a way I can replace thoses characters using python?

EDIT : in order to understand the char, when I pipe ls to xxd the ” character appears in the ascii representation. In hexadecimal it shows ‘5c’

Advertisement

Answer

This string.replace worked for me:

JavaScript

Output is:

JavaScript

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

A regular expression could also work for the general case, but you’ll have to escape the backslash so that x itself isn’t interpreted as a regular expression escape.

For the general case of removing x followed by two hexadecimal digits:

JavaScript

Output is:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement