0

I need to replace a python string that contains a number of '\':

String = 'A\BBC\CCB\:ABC'
goal = 'A/BBC/CCB/:ABC'

num = String.count('\')
String.replace('\','/')

But I keep getting error message:

SyntaxError: EOL while scanning string literal

VisioN
  • 143,310
  • 32
  • 282
  • 281
thegeek
  • 19
  • 3
  • Please escape your backslashes with a backslash, i.e. `'A\\BBC\\CCB:ABC'.replace('\\', '/')`. – VisioN Aug 19 '19 at 16:58

3 Answers3

2

The \ character in python has special uses. Eg. "\n" (newLine Character). In order to replace it in a string, you need to use one of the following:

String.replace('\\','/')
String.replace(r'\','/')

The "\" will look for the "\" character. The r'\' will look for the raw interpretation of the string '\'

Daniel Glynn
  • 584
  • 4
  • 9
  • Hey Daniel, for some reason it still doesn't work even I added 'r' – thegeek Aug 19 '19 at 18:12
  • @thegeek when you are defining your string, make sure it is being defined with the same formatting as well. String = r'A\BBC\CCB\:ABC' or String = 'A\\BBC\\CCB\\:ABC' – Daniel Glynn Aug 19 '19 at 19:03
-1

In your case you can do it like this:

string.replace('\\', '/', num)
-2

Use '\', consider this situation:

print( "He said: \"Something about her.\"" );

user3696153
  • 568
  • 5
  • 15