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\)'
9
  • Have you tried r'\'? Commented Aug 30, 2013 at 14:14
  • 1
    @thegrinner, r'\' is not a valid string. Look here Commented Aug 30, 2013 at 14:16
  • 3
    @thegrinner: that is the one thing you cannot do in a raw string. You cannot end it in one slash. Commented Aug 30, 2013 at 14:17
  • 1
    @sergei "but it inserts 2 backslashes" no, it doesn't. It only looks so for representation purposes. Commented Aug 30, 2013 at 14:18
  • 1
    @thegrinner Have you tried r'\'? Commented Aug 30, 2013 at 14:38

5 Answers 5

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).

Sign up to request clarification or add additional context in comments.

Comments

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\)

1 Comment

You got the print part right but the final result isn't like he wanted.
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.

Comments

0

Can something like this suffice?

print(s1.replace('(', '\\(').replace(')', '\\)'))

5 Comments

That doesn't answers the question.
@AshwiniChaudhary Right. I fixed it.
@AshwiniChaudhary Yes, it inserts 2 backslashes to get the second one right. Have you run the code?
I know your code works but question was why I am getting \\ in the output?(repr vs str)Add explanation related to that in your answer.
He was actually getting a SyntaxError, plus there was an issue with the index used to insert the char. Can't see any question about "why".
0
for folder in Chart_Folders:
    files = os.listdir(path + '\\' + folder)
    print(files)

indeed this works

1 Comment

This doesn't address the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.