在python中将可变长度字符串拆分为多个部分
我有一个数据库: 正如您在“desc”列中看到的,文本的长度是可变的,这意味着我从该数据库中提取的两个字符串的长度不会相同。我最终会向这个数据库添加更多的条目,但这就是我目前正在测试的内容 现在,我有以下python代码来获取这些字符串块并显示它们:在python中将可变长度字符串拆分为多个部分,python,string,string-formatting,Python,String,String Formatting,我有一个数据库: 正如您在“desc”列中看到的,文本的长度是可变的,这意味着我从该数据库中提取的两个字符串的长度不会相同。我最终会向这个数据库添加更多的条目,但这就是我目前正在测试的内容 现在,我有以下python代码来获取这些字符串块并显示它们: cmd = input(Enter command:) sql = "SELECT cmd,`desc` FROM table WHERE cmd = '"+ cmd +"'" cursor.execute(sql) result = cursor
cmd = input(Enter command:)
sql = "SELECT cmd,`desc` FROM table WHERE cmd = '"+ cmd +"'"
cursor.execute(sql)
result = cursor.fetchall()
for row in result:
print("Command: "+ row[0] +":\n")
print("Description: "+ row[1][:40] +"\n")
if (len(row[1]) > 40):
print(row[1][40:85])
if (len(row[1]) > 85):
print(row[1][85:130])
if (len(row[1]) > 130):
print(row[1][130:165])
if (len(row[1]) > 165):
print(row[1][165:])
此处的拆分在一定程度上起作用,例如:
命令:关闭:
说明:此命令将创建“关闭”按钮
n在调用字符的消息窗口中
演员。如果屏幕上当前没有窗口,t
他将结束脚本执行
正如上面的输出示例所示,拆分会导致一些字符在单词中间被截断。考虑到字符串的长度可能介于…20个字符和最多190个字符之间,并且由于空间限制,我想将字符串拆分为…8个单词的块,我该如何执行此操作?在空格上拆分以分隔单词,然后以空格作为分隔符一次连接8个单词
content = "This is some sentence that has more than eight words"
content = content.split(" ")
print content
['This', 'is', 'some', 'sentence', 'that', 'has', 'more', 'than', 'eight', 'words']
print(" ".join(content[0:8]))
This is some sentence that has more than
使用python模块按单词而不是字符剪切: 看看这本书
您可以对TextWrapper进行大量配置。这是存在的?!python标准库从未停止让我惊讶+1为了完成任务,我在耍卑鄙的把戏。我不知道有这样的东西。我一有机会一定会去看看的。谢谢它很快就能完成任务。这就是我想要的:谢谢!这就是我目前正在寻找的。使用参数替换,而不是手动构造sql字符串,例如游标。执行'select*from commands where cmd=?',cmd,。您不需要调用cursor.fetchall,您可以直接遍历它:对于cursor中的行:。。。
>>> import textwrap
>>> text = 'asdd sdfdf asdsg asfgfhj'
>>> s = textwrap.wrap(text, width=10) # <- example 10 characters
>>> s
['asdd sdfdf', 'asdsg', 'asfgfhj']
>>> print '\n'.join(s)
asdd sdfdf
asdsg
asfgfhj
>>>
>>> import textwrap
>>>
>>> s = "This command will create a 'close' button in the message window for the invoking character. If no window is currently on screen, the script execution will end."
>>>
>>> wrapped = textwrap.wrap(s, 40)
>>>
>>> for line in wrapped:
... print line
...
This command will create a 'close'
button in the message window for the
invoking character. If no window is
currently on screen, the script
execution will end.