在while循环中拆分字符串并附加到lis

2024-07-02 13:20:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本,通过一个网站自动发送短信。我使用机械化美化组4来完成此操作。在

该程序通过从命令行调用它,并将数字和消息作为参数传递;为此,我使用Optparse。在

消息通过命令行传递给程序,但网站只接受每条短消息444个字符。所以我要做的是:

  • 确定消息字符串的长度(包括空格),如果大于444,则。。。在
  • 迭代while循环,该循环获取临时消息字符串,并将索引0中总消息字符串的前444个字符追加到列表对象,直到临时消息字符串的长度不再大于444
  • 然后,通过使用list对象中的项数,我将遍历一个For循环块,该块循环处理发送消息的过程,其中每个迭代对应于444个字符字符串的索引(总消息的拆分),然后我将把444个字符的消息片段放入相应的HTML表单字段中机械化作为要发送的消息(希望这是可以理解的!)在

我目前编写的代码如下:

message = "abcdefghijklmnopqrstuvwxyz..." # imagine it is > 444 characters
messageList = []
if len(message) > 444:
    tmpMsgString = message
    counter = 0
    msgLength = len(message)

    while msgLength > 444:
        messageList.append(tmpMsgString[counter:counter+445]) # 2nd index needs to point to last character's position in the string, not "counter+445" because this would cause an error when there isn't enough characters in string?
        tmpMsgString = tmpMsgString[counter+445:msgLength])
        msgLength = msgLength-444
        counter = counter + 444
else:
    messageList.append(message)

我可以管理代码的一部分来接受来自命令行的参数,我也可以管理循环通过for循环块和使用列表中的每一项作为要发送的消息,但是我几乎没有Python经验,我需要一双有经验的眼睛来帮助我处理这部分代码!感谢大家的帮助。在


Tags: 字符串代码命令行程序消息message列表网站
2条回答

如果您只需将字符串分成444个字符块,就不需要计数器或复杂的东西。以下是如何更新当前代码:

message = "whatever..."*1000
tmp = message
msgList = []
while tmp:
    msgList.append(tmp[:444])
    tmp = tmp[444:]

这是可行的,因为跨越序列范围之外的切片将被截断到序列的末尾(不会引发IndexErrors)。如果整个切片超出边界,结果将为空。在

使用列表理解,您可能可以更好地完成此操作:

^{pr2}$

包括电池。为了演示,它使用44个字符。结果列表可以很容易地迭代。在词的边界处,而不是任意拆分。在

>>> import textwrap
>>> s = "lorem ipsum" * 20
>>> textwrap.wrap(s, width=44)
['lorem ipsumlorem ipsumlorem ipsumlorem', 'ipsumlorem ipsumlorem ipsumlorem ipsumlorem', 'ipsumlorem ipsumlorem ipsumlorem ipsumlor
em', 'ipsumlorem ipsumlorem ipsumlorem ipsumlorem', 'ipsumlorem ipsumlorem ipsumlorem ipsumlorem', 'ipsum']

相关问题 更多 >