2

I'm trying to insert a backslash in a string but when I do this:

s1='cn=Name Surname (123)'
s1[:17] + '\' + s1[17:]

I get

SyntaxError: EOL while scanning string literal

Also, tried this but it inserts 2 backslashes

s1[:17] + '\\' + s1[17:]

The final string should look like this

s1='cn=Name Surname \(123\)'
sergei
  • 73
  • 1
  • 1
  • 7

5 Answers5

5

Here:

>>> s1 = 'cn=Name Surname (123)'
>>> x = s1[:16]+'\\'+s1[16:-1]+'\\'+s1[-1:]
>>> x
'cn=Name Surname \\(123\\)'
>>> print x
cn=Name Surname \(123\)
>>>

You have to print the string. Otherwise, you will see \\ (which is used in the interpreter to show a literal backslash).

4
>>> s1='cn=Name Surname (123)'
>>> s1[:17] + '\\' + s1[17:]
'cn=Name Surname (\\123)'

It seems like two backslash, but it's actually containing only one backslash.

>>> print(s1[:17] + '\\' + s1[17:])
cn=Name Surname (\123)
>>> print s1[:17] + '\\' + s1[17:-1] + '\\' + s1[-1:]
cn=Name Surname (\123\)
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • You got the print part right but the final result isn't like he wanted. –  Aug 30 '13 at 14:18
1

If you're just entering it in the python command line interpreter and pressing enter, it will show up as two backslashes because the interpreter shows the escape character. However, if you saved it to a file, or if you used it in a "print" command it will suppress the escape character and print the actual value, which in this case is just one backslash.

CCKx
  • 1,303
  • 10
  • 22
0

Can something like this suffice?

print(s1.replace('(', '\\(').replace(')', '\\)'))
Germano
  • 2,452
  • 18
  • 25
0
for folder in Chart_Folders:
    files = os.listdir(path + '\\' + folder)
    print(files)

indeed this works

2winners
  • 1
  • 1