简体   繁体   中英

How to escape backslashes in files

I am trying to work on a script but I am stuck in one place.

Eg. To get a php output I have used..

str_php = """
<?php
echo "Hello World!";
?>"""

php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()

Ok, so I get the output as it is....

<?php
echo "Hello World!";
?>

So my php code is running. all good till here. But, the problem starts from when I try using "\\" and "\\n" and "\\r"

str_php = """
<?php
echo "Hello World!"; \n echo "How are you"; \n echo "God bless you";
?>"""

php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()

But here I dont get the output as it is.

<?php
echo "Hello World!"; 
 echo "How are you"; 
 echo "God bless you";
?>

And the "\\" it just vanishes... at an output. Eg. I want an output of a php hyperlink something like...

str_php = """<?php
print("<a href=\"$dirArray[$index]\">$dirArray[$index]</a>");
?>"""

php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()

and the output I get is...

<?php
print("<a href="$dirArray[$index]">$dirArray[$index]</a>");
?>

The "\\" is missing and the php does not run creating error.

print("<a href=\"$dirArray[$index]\">$dirArray[$index]</a>") - Original
print("<a href="$dirArray[$index]">$dirArray[$index]</a>") - python output

Can any one help me out with "\\", "\\n", "\\r" ??

Just use "\\" to escape the "\\" character.

Since it is common to want to have long strings containing several "\\", Python also allows one to prefix the string opening quotes if ar r (for "raw") - inside such a string, no escaping of "\\n" to chr(10) or "\\t" to chr(9) happens:

>>> print (r"Hello \n world!")
Hello \n world!

您需要使用另一个反斜杠来转义“\\”,将其写为“\\\\”。

If you use "\\n" it will be parsed and make a newline. Try to use '\\n' , strings enclosed in '\\n' are not parsed and it should print out as you want it to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM