相关疑难解决方法(0)

Python将\替换为\ \

所以我似乎无法弄清楚这一点......我有一个字符串说,"a\\nb"我希望这成为"a\nb".我已经尝试了以下所有,似乎没有工作;

>>> 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'
Run Code Online (Sandbox Code Playgroud)

我真的不明白为什么最后一个有效,因为这很好用:

>>> a.replace("\\","%")
'a%nb'
Run Code Online (Sandbox Code Playgroud)

这里有什么我想念的吗?

编辑我明白\是一个转义字符.我在这里要做的是将所有\\n \\t等等转换成\n \t等等,并且替换似乎没有像我想象的那样工作.

>>> a = "a\\nb"
>>> b = "a\nb"
>>> print a
a\nb
>>> print b
a
b
>>> a.replace("\\","\\")
'a\\nb'
>>> a.replace("\\\\","\\")
'a\\nb'
Run Code Online (Sandbox Code Playgroud)

我希望字符串a看起来像字符串b.但是替换不是像我想的那样替换斜线.

python string double replace slash

31
推荐指数
2
解决办法
8万
查看次数

Python 3:如何获得字节字符串的字符串文字表示?

在Python 3中,如何将字节字符串插入到常规字符串中并获得与Python 2相同的行为(即:只获取没有b前缀或双反斜杠的转义码)?

例如:

Python 2.7:

>>> x = u'\u041c\u0438\u0440'.encode('utf-8')
>>> str(x)
'\xd0\x9c\xd0\xb8\xd1\x80'
>>> 'x = %s' % x
'x = \xd0\x9c\xd0\xb8\xd1\x80'
Run Code Online (Sandbox Code Playgroud)

Python 3.3:

>>> x = u'\u041c\u0438\u0440'.encode('utf-8')
>>> str(x)
"b'\\xd0\\x9c\\xd0\\xb8\\xd1\\x80'"
>>> 'x = %s' % x
"x = b'\\xd0\\x9c\\xd0\\xb8\\xd1\\x80'"
Run Code Online (Sandbox Code Playgroud)

注意如何使用Python 3,我b在输出中获得前缀和双下划线.我想得到的结果是我在Python 2中获得的结果.

python escaping python-3.x

7
推荐指数
2
解决办法
7063
查看次数

标签 统计

python ×2

double ×1

escaping ×1

python-3.x ×1

replace ×1

slash ×1

string ×1