在Python中将变长字符串分割成多个部分

7 投票
3 回答
6614 浏览
提问于 2025-04-17 10:19

我有一个数据库:

从“desc”这一列可以看到,里面的文字长度不一样(也就是说,从这个数据库里取出来的字符串长度都不相同)。我最终会往这个数据库里添加更多的条目,但现在我先用这些数据进行测试。

目前,我有以下的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:])

这里的分割在某种程度上是有效的,比如:

命令:close:
描述:这个命令会在消息窗口为调用者创建一个“关闭”按钮
如果当前没有窗口在屏幕上,脚本执行将结束。

从上面的输出例子可以看到,分割导致一些字符在单词中间被截断。考虑到这些字符串的长度可能在20个字符到190个字符之间,而我想把字符串分成每8个单词一块,因为空间有限,我该怎么做呢?

相关问题:

3 个回答

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模块

>>> 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进行很多设置。

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

撰写回答