python3:如何将“ \ u3000”(表意空间)转换为“”?

问题描述 投票:0回答:2

japanese.txt

あかさ
あいうえ お
いい

mycode.py

with open('japanese.txt', 'r', encoding='utf-8') as f:
    old = [line.strip() for line in f.readlines()]

send_mail(from, to, title, message=f"hello {old}!")

然后我收到这样的邮件

hello ['あかさ', 'あいうえ\u3000お', 'いい']!

我想邮寄的是这个

hello ['あかさ', 'あいうえ お', 'いい']!

我该如何实现?

python-3.x python-unicode
2个回答
1
投票

\ u3000是Unicode中的“表意空间”,您可以尝试将其替换:

with open('japanese.txt', 'r', encoding='utf-8') as f:
    old = [line.strip().replace(u'\u3000',u' ') for line in f.readlines()]

send_mail(from, to, title, message=f"hello {old}!")

0
投票

列表的__str__方法在元素上使用repr,因此您在邮件中看到\u3000。只需将列表转换为字符串即可:

In [28]: l = ['あかさ', 'あいうえ\u3000お', 'いい']

In [29]: print(', '.join(map(str, l)))
あかさ, あいうえ お, いい

如果您确定所有列表元素都是字符串,则可以省略map(str, ...),而只需使用', '.join(l)

© www.soinside.com 2019 - 2024. All rights reserved.