TGWaffles TGWaffles - 1 year ago 88
Python Question

How would I find the nearest space per every 2000 characters and add everything before it to a variable? (Python)

I'm currently writing a program that posts messages with a 2,000 character limit. The string I'm using is usually around 10,000 characters. However, the method I'm using to divide it up can divide the string up in the middle of a word - how would I only have it divide at the nearest space (BEFORE) 2k characters?

Here's the current code:

text = str(post.selftext)
title = await client.send_message(, str(post.title))
if len(text) > 1990:
amountsplit = math.ceil(len(text) / 1990)
atatime = math.floor(len(text) / amountsplit)
donetimes = 0
lastone = 0
for i in range(amountsplit):
todonow = int(donetimes + 1) * atatime
tmp = await client.send_message(, str(text[lastone:todonow]))
lastone = todonow
donetimes += 1

Answer Source

U can use rfind() method of str:

from __future__ import print_function

def split_message(message, character_limit=2000):
    messages = []

    while len(message) > character_limit:
        split_index = message[:character_limit].rfind(" ")
        if split_index == -1:
            # No space found, just split at the character limit
            split_index = character_limit
            # Else space is found, split after the space
            split_index += 1
        message = message[split_index:] 
    return messages

# Test code 
test_string = "this  is a test string to see if this works right"
test_string = "thisisateststringwithnospaces"

for character_limit in range(1, 10):
    print ("limit", character_limit, ": ", split_message(test_string, character_limit))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download