【问题标题】:Splitting a variable length string into multiple parts in python在python中将可变长度字符串拆分为多个部分
【发布时间】:2012-01-15 23:11:11
【问题描述】:

我有一个数据库:

正如您在 '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:])

这里的拆分在一定程度上起作用,例如:

命令:关闭:
说明:此命令将创建一个“关闭”按钮
n 在调用字符的消息窗口中
演员。如果屏幕上当前没有窗口,t
他的脚本执行将结束。

正如您在上面的输出示例中看到的那样,拆分会导致一些字符在单词中间被截断。鉴于字符串的长度可以是介于...20 个总字符和最多 190 个之间的任何长度,并且由于空间限制,我想将字符串分成多个...8 个单词的块,我将如何去关于这样做?

【问题讨论】:

  • 使用参数替换而不是手动构造 sql 字符串,例如 cursor.execute('select * from commands where cmd=?', (cmd,))。你不需要调用cursor.fetchall(),你可以直接迭代它:for row in cursor: ...

标签: python string string-formatting


【解决方案1】:

查看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 可以做很多配置。

【讨论】:

  • 这存在吗?! python 标准库永远不会让我感到惊讶。 +1
  • 我正在研究一个肮脏的伎俩来完成工作。我不知道有这样的东西。有机会我一定会去看看的。谢谢!
  • 速度很快,可以完成工作。这就是我一直在寻找的:)
【解决方案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

【讨论】:

  • 谢谢!这就是我目前正在寻找的东西。
【解决方案3】:

使用 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
>>> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    相关资源
    最近更新 更多