【发布时间】:2018-01-09 17:26:30
【问题描述】:
我有一个向一个或多个收件人发送短信和文件的功能。在 Python 2 中有一个全局发送者对象,它接受文本和接收者配置作为 Python 2 中的 unicode 对象和 Python 3 中的字符串对象。这是现在的函数,并且与 Python 2 兼容:
def send_message_Telegram(
recipient = None, # string
recipients = None, # list of strings
text = None,
filepath = None
):
if text and not filepath:
if recipient:
tg_sender.send_msg(
unicode(recipient),
unicode(text)
)
if recipients:
for recipient in recipients:
tg_sender.send_msg(
unicode(recipient),
unicode(text)
)
if filepath and not text:
if recipient:
tg_sender.send_file(
unicode(recipient),
unicode(filepath)
)
if recipients:
for recipient in recipients:
tg_sender.send_file(
unicode(recipient),
unicode(filepath)
)
如果我希望这个函数与 Python 3 兼容,我必须将 unicode() 的所有用法更改为 str()。我需要该函数在 Python 2 和 Python 3 中都可以工作,那么应该如何更改它呢?我不想到处写这样的代码:
if sys.version_info >= (3, 0):
tg_sender.send_msg(
str(recipient),
str(text)
)
else:
tg_sender.send_msg(
unicode(recipient),
unicode(text)
)
就像,这是我目前最好的,但看起来很奇怪:
def ustr(text):
if text is not None:
if sys.version_info >= (3, 0):
return str(text)
else:
return unicode(text)
else:
return text
def send_message_Telegram(
recipient = None, # string
recipients = None, # list of strings
text = None,
filepath = None
):
if text and not filepath:
if recipient:
tg_sender.send_msg(
ustr(recipient),
ustr(text)
)
if recipients:
for recipient in recipients:
tg_sender.send_msg(
ustr(recipient),
ustr(text)
)
if filepath and not text:
if recipient:
tg_sender.send_file(
ustr(recipient),
ustr(filepath)
)
if recipients:
for recipient in recipients:
tg_sender.send_file(
ustr(recipient),
ustr(filepath)
)
【问题讨论】:
标签: string python-3.x unicode