2012-01-15 45 views
6

多个部分我有一个数据库:拆分可变长度字符串转换成在python

正如你可以在“说明”一栏看到,该文本是可变长度(意味着没有两个字符串我的从这个数据库拉将会是相同的长度)。我最终会在这个数据库中添加更多条目,但这是我正在测试的内容,现在开始。

现在,我有以下Python代码抢串的这些块,并显示它们:

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:]) 

这里的拆分工作到一定程度,例如:

命令:关闭:
说明:该命令将在调用char
acter的消息窗口中创建'close',但将生成
n。如果当前没有窗口在屏幕上,那么脚本执行将结束。

正如您在上面的输出示例中看到的那样,分割会导致某些字符在中间词中被截断。鉴于这些字符串的长度可能在20个字符之间,最多为190个字符之间,我想将字符串分成几块......每个字8个字,因为空间限制,我将如何去关于这样做?

+0

使用参数替换而不是手动构建sql字符串,例如'cursor.execute('select * from cmd =?',(cmd,))''。你不需要调用'cursor.fetchall()'你可以直接遍历它:'对于游标中的行:...' – jfs 2012-01-16 00:18:13

回答

2

将空格拆分以分隔单词,然后每次连接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 
+0

谢谢!这就是我现在正在寻找的东西。 – Jguy 2012-01-15 23:30:06

1

削减使用python textwrap模块的词代替字符:

>>> 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 
>>> 
16

退房的textwrap module

>>> 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. 

你可以做很多TextWrapper的配置。

+0

TIL textwrap,非常有用 – JustinDanielson 2012-01-15 23:19:41

+0

这存在吗?! Python标准库永远不会让我感到惊讶。 +1 – senderle 2012-01-15 23:22:07

+0

我正在研究一个肮脏的伎俩来完成工作。我不知道这样的东西是可用的。一旦我有机会,我一定会看看。谢谢! – Jguy 2012-01-15 23:28:35