私は少しあなたの例を再生し、甘い..
まずオフ:バイトから変換するにはstr()
を使用していない、結果はあなたが期待するかもしれないものではありません。
>>> str(b'abcd')
"b'abcd'"
Pythonは単に入力の文字列表現は、いくつかの他の文字列にバイトを置きます。
次のように変換します。私はあなたのmsg
をシミュレートするために、いくつかの単純なクラスを書いた
>>> b'abcd'.decode('utf-8')
'abcd'
:
class Obj:
def __init__(self, **kwargs):
[setattr(self, k, v) for k, v in kwargs.items()]
msg = Obj(
content='some text',
author=Obj(
id='1337', name='some author'
),
channel=Obj(
server=Obj(name='localhost'),
name='#some_channel',
),
)
第二:ログ機能のウィッヒを作成した情報をmsg
オブジェクトを受け取り、出力します:
def log_msg(msg):
content = msg.content
return '''Message: \
{content} \
by {author_name} ({author_id}) \
@ {server_name} \
in {channel_name}'''.format(
content=content,
author_name=msg.author.name,
author_id=msg.author.id,
server_name=msg.channel.server.name,
channel_name=msg.channel.name,
)
出力文字列を構成するには、複数行の文字列''' ... '''
とstr.format()を使用します。私はあなたのサンプルデータを使用している場合
print(log_msg(msg))
>>> Message: some text by some author (1337) @ localhost in #some_channel
今、何かが起こります:
は、今私が行うことができます
msg.content = '\xe2\x9d\xa4'
print(log_msg(msg))
>>> Message: ⤠by some author (1337) @ localhost in #some_channel
は奇妙に見えますが、あなたはどこかにコードポイントを見れば、すべてが大丈夫です:
\xe2; \x9d; \xa4
しかし、我々はそこにバイトを扱っているので、これは、間違っている:
msg.content = b'\xe2\x9d\xa4'
print(log_msg(msg))
>>> Message: b'\xe2\x9d\xa4' by some author (1337) @ localhost in #some_channel
また、これは間違っている、我々は、入力の文字列表現は、ここでバイトを取得します。
印刷する前に変換を行いますので、ログ機能の開始を変更します。
def log_msg(msg):
content = msg.content
if not isinstance(content, str):
content = content.decode('utf-8')
return '''Message: \
...
そして、この参照:データ型(バイト、STRを混同していない、だから、
msg.content = b'\xe2\x9d\xa4'
print(log_msg(msg))
>>> Message: ❤ by some author (1337) @ localhost in #some_channel
を)変換の順番を混同しないでください。❤
テキストのスクリーンショットではなく、実際のテキストをご使用ください。質問を編集してスクリーンショットを削除し、実際のテキストに置き換えることができます。 – marcelm
修正しました、申し訳ありません。 – ImUniverseSE
文字列をエンコードしないで直接印刷してください。 Python 3の 'print'は自動的にエンコーディングを行います。そうでなければ、それは別の問題です。 –