Hướng dẫn replace slash in python

I wrote this simple little program:

def main ( ):
with open("test.txt", "rt") as fin:
    with open("out.txt", "wt") as fout:
            for line in fin:
                fout.write(line.replace("\", "/"))
print ("done")

main ()

I know that "\" is an escape literal in Python but all I need is to scan through the text file and replace every single backlash with a forward slash "/".

Anyone knows what to do?

asked Feb 26, 2017 at 7:19

2

You have to remember that strings in python are interpreted. Only raw strings do not follow this rule. Here I mean that if for example you have a "\n" included in your string, it would be interpreted as a new line. Fortunately strings read from file are already raw.

All you have to do is simply use the regular expression:

s.replace('\\','/')

answered Feb 26, 2017 at 7:20

adgon92adgon92

2091 silver badge6 bronze badges

3

Not the answer you're looking for? Browse other questions tagged python file escaping backslash or ask your own question.

  • Using replace()
  • Using translate() function
  • Using regular expression (re.sub())
  • Backslash in Python
  • Method 1: Using the inbuilt String replace() function
  • Method 2: Using translate() function in Python
  • Method 3: Using regular expression (re.sub()) in Python

A forward-slash (/) in a Python string can be replaced by a backslash (\) using the String replace() function, translate() method, or regular expression(re.sub()).

Contents

  • 1 Using replace()
  • 2 Using translate() function
  • 3 Using regular expression (re.sub())
  • 4 Backslash in Python
  • 5 Method 1: Using the inbuilt String replace() function
  • 6 Method 2: Using translate() function in Python
  • 7 Method 3: Using regular expression (re.sub()) in Python

Using replace()

example_string = "path/to/check"
new_string = example_string.replace("/", "\\")
print(new_string)

Output:

path\to\check

Using translate() function

stringn = "book/pencil/ink/pen/rubber"
stringn1 = stringn.translate(str.maketrans({'/': '\\'}))
print(stringn1)

Output:

book\pencil\ink\pen\rubber

Using regular expression (re.sub())

import re
string1 = "path/to/check/and/edit"
string2 = re.sub("/", r"\\", string1)
print(string2)

Output:

path\to\check\and\edit

To get more details about those concepts, continue reading on. There is more to learn. First of all, let’s discuss backslash.

In Python, the backslash is a special character.  First of all, it is used as part of a special character sequence; for example, “\n” means move to the next line, “\b” is the backspace character, and “\t” is tab space in Python code. In these cases, Python considers the sequence of characters as a single character in each case.

Secondly, a backslash can be used as an escape character – in this case, when a backslash is placed in front of a particular character, it changes the meaning of that character. In fact, backslash in Python is represented as “\\”.

print("\")

Output: syntax error: unterminated string literal

print("\\")

Output:

\

In the first print statement, the backslash changes the meaning of the second quotation from being a closing quotation to being a literal string character hence the error “unterminated string literal”. Therefore, print(“example\”string”) will output example”string because the second quotation marks have been rendered literal string character by the escape character -the backslash.

Once the concept of representing backslash in Python is clear, we can now discuss how to replace forward-slash with a backslash.

Method 1: Using the inbuilt String replace() function

The general syntax for replace() function is:

example_string.replace(old_substring, new_substring, count)

Where count is an optional argument representing the number of occurrences of the old_substring to be replaced. By default, the function replaces all occurrences of the given substring.

example_string = "Python/programming/language"
new_string = example_string.replace("/", "\\")
print(new_string)

Output:

Python\programming\language

Note: replace() string returns a copy of the string after making the replacement, and therefore, the example_string variable will still have the original string even after execution.

Method 2: Using translate() function in Python

The translate() function allows one to replace one or multiple characters which should be provided in a dictionary as shown below. The code replaces forward-slash (/) and “e” in a string with a backslash.

stringn = "book/pencil/ink/pen/rubber"
stringn1 = stringn.translate(str.maketrans({'/': '\\', "e": "\\"}))
print(stringn1)

Output:

book\p\ncil\ink\p\n\rubb\r

Note that the keys for the translate dictionary must be a single character otherwise, you will run into an error.

Method 3: Using regular expression (re.sub()) in Python

As the name suggests, the pre-installed re package works with regular expressions to detect patterns in strings. The package has a function sub() that can be used to find and substitute substrings. For example,

import re 
string1 = "Python/programming/language/3.10"
string2 = re.sub("/", "\\\\", string1)
print(string2)

Output:

Python\programming\language\3.10

In the re module, we need to pass “\\\\” as the pattern to capture a single backslash.

Reason: In the package, the backslash is also used as an escape character, and therefore, we need to pass “\\”, and since we also need “\\” for a Python literal string, then a valid pattern for a backslash is “\\\\”.

Alternatively, we can use raw string formatting (they are strings preceded by r), which converts backslash into a literal string. Note that, in the code, we still use “\\”, because the raw string only applies to the re pattern but we still need to write backslash as “\\”

import re
string1 = "Python/programming/language/3.10"
string2 = re.sub("/", r"\\", string1)
print(string2)

Output:

Python\programming\language\3.10

Hướng dẫn replace slash in python