Skip to main content
 首页 » 编程设计

python之在 Python 2.7 中拆分字符串

2024年11月01日26bjzhanghao

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

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!') 

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

请您参考如下方法:

我不太清楚你在问什么,但看起来这会做你想要的。
假如说 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)