Home > Enterprise >  Insert a backslash before special character in a string using python or shell script
Insert a backslash before special character in a string using python or shell script

Time:07-08

Is it possible to insert a backslash when a special character appears on string ?

Raw String: echo "The string is: Ytds^&4"

Output expected: echo "The string is: Ytds\^\&4"

Can I use python or shell.

CodePudding user response:

You could use a manual chain of .replace(), which would be messy.

You could also just use a function like this:

str_ = "Y^541" 


def change(string: str, characters): 
    for character in characters:
        string = string.replace(character, "\\"   character)
    return string


print(change(str_, "!@#$%^&*()")) # output: Y\^541

The argument characters should be a string of all the characters which are considered as special, and it does a loop to replace each of those characters with a backslash.

CodePudding user response:

In Python, the following will produce exactly the required output:

print('The string is: Ytds\^\&4')

This is because neither the caret nor the ampersand are escapable characters and therefore the backslash is interpreted literally giving this output:

The string is: Ytds\^\&4
  • Related