简体   繁体   中英

Replace forward slash with a sequence of back and forward slash

I want to replace a sequence of forward slash such as '//' with '\/'. For example: 'http://www.test.com/' should return 'http:\/\/www.test.com\/' I have tried a few commands in python such as the examples below, but haven't been successful yet:

myString.replace(r'/',r'\\/') returns 'http:\\\\/\\\\/www.test.com.br\\\\/'

myString.replace(r'/','\\\/') also returns 'http:\\\\/\\\\/www.test.com.br\\\\/'

How can I obtain the result that I need?

I am using Python 3.8

When you use a raw string, the backslash is no longer used as an escape character, and everything shows up in the string just as you typed it (you still can't end a string with a backslash, though). You only need to double it up if you're not using raw strings. Also, the result you saw was directly returned in an interactive session, which means you saw the repr of that string - meaning, it's telling you what you'd need to type in to produce the same object. Don't overdo it with raw strings and backslashes, and use print .

>>> myString = 'http://www.test.com/'
>>> print(mystring.replace('/', r'\/'))
http:\/\/www.test.com\/

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