Найти - Пользователи
Полная версия: разбить строку в список, алгоритм
Начало » Python для новичков » разбить строку в список, алгоритм
1
ilnur
привет.
есть строка
a=u'здесь очень длинный текст который надо разбить'
как бы мне его разделить в список, чтобы каждый элемент списка не был больше 23, и слова не переносились
т.е. получить
list=[u'здесь очень длинный', u'текст который надо', u'разбить']
fata1ex
a = 'We use cookies to ensure that we give you the best experience on our website. We also use cookies to ensure we show you advertising that is relevant to you. If you continue without changing your settings, we\'ll assume that you are happy to receive all cookies on the BBC website. However, if you would like to, you can change your cookie settings at any time.'
result = []
bufstr = ''
 
for dig in a:
    bufstr += dig
    if len(bufstr) > 23:
        to_append, bufstr = bufstr.rsplit(' ', 1)
        result.append(to_append)
 
result.append(bufstr)
print map(len, result), result

[17, 23, 22, 20, 21, 23, 19, 20, 21, 22, 21, 22, 16, 21, 23, 23, 9] ['We use cookies to', 'ensure that we give you', 'the best experience on', 'our website. We also', 'use cookies to ensure', 'we show you advertising', 'that is relevant to', 'you. If you continue', 'without changing your', "settings, we'll assume", 'that you are happy to', 'receive all cookies on', 'the BBC website.', 'However, if you would', 'like to, you can change', 'your cookie settings at', 'any time.']

В фреймворках существуют специальные функции для таких вещей.
ilnur
to_append, bufstr = bufstr.rsplit(' ', 1)
а что значит параметр 1?
fata1ex
http://docs.python.org/library/stdtypes.html#str.rsplit
pyuser
А чем модуль textwrap не угодил?
Virtuos86
наш пострел везде поспел :)
ilnur
Virtuos86
наш пострел везде поспел :)
т.е.?
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB