Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

string - Python Replace \ with

So I can't seem to figure this out... I have a string say, "a\nb" and I want this to become "a b". I've tried all the following and none seem to work;

>>> a
'a\nb'
>>> a.replace("","")
  File "<stdin>", line 1
    a.replace("","")
                      ^
SyntaxError: EOL while scanning string literal
>>> a.replace("",r"")
  File "<stdin>", line 1
    a.replace("",r"")
                       ^
SyntaxError: EOL while scanning string literal
>>> a.replace("",r"")
'a\\nb'
>>> a.replace("","")
'a\nb'

I really don't understand why the last one works, because this works fine:

>>> a.replace("","%")
'a%nb'

Is there something I'm missing here?

EDIT I understand that is an escape character. What I'm trying to do here is turn all \n \t etc. into etc. and replace doesn't seem to be working the way I imagined it would.

>>> a = "a\nb"
>>> b = "a
b"
>>> print a
a
b
>>> print b
a
b
>>> a.replace("","")
'a\nb'
>>> a.replace("","")
'a\nb'

I want string a to look like string b. But replace isn't replacing slashes like I thought it would.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's no need to use replace for this.

What you have is a encoded string (using the string_escape encoding) and you want to decode it:

>>> s = r"Escaped
Newline"
>>> print s
Escaped
Newline
>>> s.decode('string_escape')
'Escaped
Newline'
>>> print s.decode('string_escape')
Escaped
Newline
>>> "a\nb".decode('string_escape')
'a
b'

In Python 3:

>>> import codecs
>>> codecs.decode('\n\x21', 'unicode_escape')
'
!'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...