【问题标题】:TypeError: Can't convert 'list' object to str implicitly - PythonTypeError:无法将“列表”对象隐式转换为 str - Python
【发布时间】:2020-02-24 13:41:23
【问题描述】:

以下是将电子邮件输入标准输入的代码,并进行一些过滤以从电子邮件中提取票证 ID,然后将其发送到电报。 但是当我运行代码时,它会返回以下错误类型。

TypeError: 无法将 'list' 对象隐式转换为 str

我已将 tikid 发送至 str(tikid),我没有收到任何问题,但没有消息发送到电报功能。

代码是:

import re
import sys
import requests

def telegram_bot_sendtext(bot_message):
    bot_token = 'mytoken_id_here'
    bot_chatID = 'my_chatid_here'
    send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message

    response = requests.get(send_text)
    return response.json()

for myline in sys.stdin:
      tikid = re.findall("ticket/\d+", myline)
      if (len(tikid)) > 0:
          tikid = output.replace("ticket/", "")
          print(tikid)

telegram_bot_sendtext(tikid)

电子邮件内容

--===============7235995302665768439==
Content-Type: text/html; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 8bit

<div dir="rtl"><html>
<head>
   Ticket generated ....     
</head>

<p>&nbsp;</p>

<p><a href="http://example.com/show/ticket/1735" target="_blank">http://example.com/show/ticket/1735</a></p>
</body>
</html>
</div>
--===============7235995302665768439==--

输出

root@server:~# cat email.txt | /usr/bin/python3.5 /usr/local/scrip/telegram-piper

1735
1735
Traceback (most recent call last):
  File "/usr/local/scripts/telegram-piper.py", line 22, in <module>
    telegram_bot_sendtext(tikid)
  File "/usr/local/scripts/telegram-piper.py", line 9, in telegram_bot_sendtext
    send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message
TypeError: Can't convert 'list' object to str implicitly```

【问题讨论】:

  • 你在哪一行得到错误?
  • 在询问有关错误的问题时,始终包括输出的完整和完整的复制粘贴。并在发生错误的行上添加注释。也请花一些时间阅读how to ask good questions,以及this question checklist
  • 您能否还包括预​​期的输入和所需的输出(如果适用)
  • 请通过编辑在问题本身中添加该信息。在标签行的正下方有一个名为edit 的链接。
  • bot_message 是一个列表,而不是一个字符串。它包含什么?

标签: python python-3.x


【解决方案1】:

解决了这个问题。 通过使用''.join

import re
import sys
import requests

def telegram_bot_sendtext(bot_message):
    bot_token = 'mytoken_id_here'
    bot_chatID = 'my_chatid_here'
    send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message

    response = requests.get(send_text)
    return response.json()

for myline in sys.stdin:
      tikid = re.findall("ticket/\d+", myline)
      if (len(tikid)) > 0:
         output = str(tikid[0])
         tikid = output.replace("ticket/", "")
         new_value=''.join(tikid)


telegram_bot_sendtext(new_value)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 2012-11-19
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多