2

我想知道如何在 Python 中允许多个输入。
例如:如果消息是“!comment postid customcomment”
,我希望能够获取该帖子 ID,将其放在某个地方,然后是 customcomment,然后将其放在其他地方。
这是我的代码:

import fb
token="access_token_here"
facebook=fb.graph.api(token)

#__________ Later on in the code: __________

                elif msg.startswith('!comment '):
                    postid = msg.replace('!comment ','',1)
                    send('Commenting...')
                    facebook.publish(cat="comments", id=postid, message="customcomment")
                    send('Commented!')

我似乎无法弄清楚。
提前谢谢你。

4

1 回答 1

2

我不能完全说出你在问什么,但似乎这会做你想要的。
假设 msg = "!comment postid customcomment" 您可以使用内置的字符串方法split将字符串转换为字符串列表,使用" "作为分隔符和最大拆分数为 2:

msg_list=msg.split(" ",2)

第零个索引将包含“!comment”,因此您可以忽略它

postid=msg_list[1]或者postid=int(msg_list[1])如果您需要数字输入

message = msg_list[2]

如果您不限制拆分并仅使用默认行为(即msg_list=msg.split()),则您必须重新加入由空格分隔的其余字符串。为此,您可以使用内置的字符串方法join来执行此操作:

message=" ".join(msg_list[2:])

最后

facebook.publish(cat="comments", id=postid, message=message)

于 2014-01-13T14:16:45.433 回答