如何在 python 中去掉字符串中的 b 前缀?

我有一个前缀为 b 的字符串:

b'I posted a new photo to Facebook'

我猜 b表示它是一个字节字符串。

如何删除这个 b前缀? 我试过:

b'I posted a new photo to Facebook'.encode("utf-8").decode("utf-8")

但这给出了一个错误:

UnicodeEncodeError: 'charmap' codec can't encode characters in position 64-65: character maps to <undefined>
207612 次浏览

您需要对其进行解码以将其转换为字符串。

b'I posted a new photo to Facebook'.decode('utf-8')
# 'I posted a new photo to Facebook'

我只用 utf-8对输出进行了编码。 下面是代码示例

new_tweets = api.GetUserTimeline(screen_name = user,count=200)
result = new_tweets[0]
try: text = result.text
except: text = ''


with open(file_name, 'a', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(text)

即: 在从 api 收集数据时不要进行编码,只对输出进行编码(打印或写入)。

要打印的对象不是字符串,而是作为 字节文字bytes对象。

考虑通过输入一个字节文字(字面上定义一个字节对象而不实际使用一个字节对象,例如输入 b”)来创建一个 字节对象,并将其转换成用 utf-8编码的 字符串对象。(注意,在这里转换意味着 解码)

byte_object= b"test" # byte object by literally typing characters
print(byte_object) # Prints b'test'
print(byte_object.decode('utf8')) # Prints "test" without quotations

我们只是应用了 .decode(utf8)函数。


字符串文字由以下词法定义描述:

Https://docs.python.org/3.3/reference/lexical_analysis.html#string-and-bytes-literals

stringliteral   ::=  [stringprefix](shortstring | longstring)
stringprefix    ::=  "r" | "u" | "R" | "U"
shortstring     ::=  "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring      ::=  "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::=  shortstringchar | stringescapeseq
longstringitem  ::=  longstringchar | stringescapeseq
shortstringchar ::=  <any source character except "\" or newline or the quote>
longstringchar  ::=  <any source character except "\">
stringescapeseq ::=  "\" <any source character>


bytesliteral   ::=  bytesprefix(shortbytes | longbytes)
bytesprefix    ::=  "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
shortbytes     ::=  "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
longbytes      ::=  "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
shortbytesitem ::=  shortbyteschar | bytesescapeseq
longbytesitem  ::=  longbyteschar | bytesescapeseq
shortbyteschar ::=  <any ASCII character except "\" or newline or the quote>
longbyteschar  ::=  <any ASCII character except "\">
bytesescapeseq ::=  "\" <any ASCII character>

尽管这个问题已经很老了,但我认为它可能对面临同样问题的人有所帮助。这里的文本是一个字符串,如下所示:

text= "b'I posted a new photo to Facebook'"

因此您不能通过编码来删除 b,因为它不是一个字节。我做了下面这些来移除它。

cleaned_text = text.split("b'")[1]

这将给 "I posted a new photo to Facebook"

在使用 django 2.0的 python 3.6上,对字节文字进行解码不能像预期的那样工作。 是的,我得到了正确的结果,当我打印它,但 b'value'仍然存在,即使你打印它的权利。

这就是我编码的东西

uid': urlsafe_base64_encode(force_bytes(user.pk)),

这就是我要解码的:

uid = force_text(urlsafe_base64_decode(uidb64))

Django 2.0是这么说的:

urlsafe_base64_encode(s)[source]

在 base64中编码字节串以用于 URL,去掉任何尾随的等号。

urlsafe_base64_decode(s)[source]

对 base64编码的字符串进行解码,并添加可能已被剥离的任何尾随等号。


这是我的 account _ activation _ email _ test.html 文件

{% autoescape off %}
Hi \{\{ user.username }},


Please click on the link below to confirm your registration:


http://\{\{ domain }}{% url 'accounts:activate' uidb64=uid token=token %}
{% endautoescape %}

这是我的控制台反应:

Content-Type: text/platin; charset = “ utf-8”MIME-Version: 1.0 内容传输编码: 7位主题: 激活您的 MySite 帐户 发信人: webmaster@localhost 致: testuser@yahoo.com 日期: 4月20日,星期五 2018年6月26日: 26:46 -0000留言-ID: & lt; 152420560682.16725.4597194169307598579@Dash-U & gt;

嗨,测试用户,

请按以下连结确认登记:

http://127.0.0.1:8000/activate/b'MjU'/4vi-fasdtRf2db2989413ba/

你可以看到 uid = b'MjU'

预期 uid = MjU


控制台测试:

$ python
Python 3.6.4 (default, Apr  7 2018, 00:45:33)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
>>> from django.utils.encoding import force_bytes, force_text
>>> var1=urlsafe_base64_encode(force_bytes(3))
>>> print(var1)
b'Mw'
>>> print(var1.decode())
Mw
>>>

经过调查,它似乎与巨蟒3有关。 我的解决办法很简单:

'uid': user.pk,

我在激活函数中接收它为 uidb64:

user = User.objects.get(pk=uidb64)

瞧瞧:

Content-Transfer-Encoding: 7bit
Subject: Activate Your MySite Account
From: webmaster@localhost
To: testuser@yahoo.com
Date: Fri, 20 Apr 2018 20:44:46 -0000
Message-ID: <152425708646.11228.13738465662759110946@Dash-U>




Hi testuser,


Please click on the link below to confirm your registration:


http://127.0.0.1:8000/activate/45/4vi-3895fbb6b74016ad1882/

现在好了。

如何删除在 python 中解码的字符串 b' '字符:

import base64
a='cm9vdA=='
b=base64.b64decode(a).decode('utf-8')
print(b)

假设您不想像其他人建议的那样立即再次解码它,那么您可以将它解析为一个字符串,然后只需去掉前面的 'b和后面的 '

x = "Hi there 😄"
x = "Hi there 😄".encode("utf-8")
x # b"Hi there \xef\xbf\xbd"
str(x)[2:-1]
# "Hi there \\xef\\xbf\\xbd"

除了@hiro 主角的回答,你还可以通过提供字符集到 str来将 bytes转换成 string:

b = b'1234'
str(b,'utf-8') # '1234'