如何将一个非常长的字符串拆分为python中较短字符串的列表
作者:互联网
在我目前的django项目中,我有一个存储非常长字符串的模型(每个数据库条目可以是5000-10000甚至更多字符)然后我需要在用户调用记录时拆分它们(它确实需要在一个记录在数据库中).我需要的是返回一个列表(queryset?取决于是否在“SQL”部分或者按原样获取所有列表并在视图中进行解析)更短的字符串(列表中每个sting 100到500个字符我返回到模板).
我无法在任何地方找到python split命令,也没有示例或任何类型的答案….
我可以随时计算单词并附加但计算单词….但我确信必须有某种功能来处理这类事情….
编辑:谢谢大家,但我想我不明白,
Example:
The String: “This is a very long string with many many many many and many more sentences and there is not one character that i can use to split by, just by number of words”
该字符串是django模型的textField.
我需要拆分它,让我说每5个字,所以我会得到:
[‘这是一个非常长的字符串’,’有许多很多’,’还有更多的句子和’,’没有一个字符’,’我可以用’,’分开,只是数字’ ,’的话’]
The thing is that is almost every programming languages there is split per number of words” kind of utility function but i can’t find one in python.
谢谢,
埃雷兹
解决方法:
>>> s = "This is a very long string with many many many many and many more sentences and there is not one character that i can use to split by, just by number of words"
>>> l = s.split()
>>> n = 5
>>> [' '.join(l[x:x+n]) for x in xrange(0, len(l), n)]
['This is a very long',
'string with many many many',
'many and many more sentences',
'and there is not one',
'character that i can use',
'to split by, just by',
'number of words']
标签:python-2-6,python,django,django-queryset 来源: https://codeday.me/bug/20190723/1516021.html