skip to Main Content

I have returned from one function as plain multi-line text, which I should print in Telegram or Discord. The problem is the character limit for one message. And text should only be separated by line. E.g.

limit = 50

text = "Line1 - some text 
Line2  - some text
Line3 - some text, limit here
Line4 - some text"

I need to do smth to get

text1 = "Line1 - some text 
Line2  - some text"

text2 = "Line3 - some text, limit here
Line4 - some text"

or any other way to separate long string onto several parts, but only by lines.

This is the wrong result:

text1 = "Line1 - some text 
Line2  - some text 
Line3 - some"

text2 = "text, limit here
Line4 - some text"

2

Answers


  1. A simple solution would be something like

    def send(x):
        #put your sending code here
        print(x)
    
    s = "10n1n101n10n1" #example input
    
    s= s.split("n") # divides the string into lines
    print(s)
    #we want to send as many lines as possible without the total size of the sent string being over limit
    limit = 3 #make this whatever you want
    sending = ""
    total = 0
    
    for line in s:
        if total + len(line) > limit:
            send(sending[:-1])
            total = len(line)
            sending = line + "n"
        else:
            total += len(line)
            sending += line + "n"
    #need to send the final string; there is probably a better way to do this, especially because this will break if the first if is entered on the last iteration
    send(sending[:-1])
    

    I suspect theres a better way to do this in just a few lines with some clever splitting or regex, but this is a brute way to split it up into smaller messages by line. Note that this will attempt to send lines that are over the character limit, and it can definitely be improved.

    Login or Signup to reply.
  2. simple example to split data to buffer

    import re
    
    limit = 50
    text = "Line1 - some textnLine2  - some textnLine3 - some text, limit herenLine4 - some text"
    tring_array=re.split('(n)(rn)',text)
    
    message=""
    for current_str in string_array:
        if (len(message)+len(current_str)+1) <= limit:
            message+=(current_str+'n')
        else:
            if len(message) == 0:
                print "buffer to smal or empty string"
                break
            else:
                print "Message: %sSize: %d" % (message,len(message))
                message=current_str+'n'
    
    if len(message)>0:
        print "Message: %sSize: %d" % (message,len(message))
    

    results

    Message: Line1 - some text
    Line2  - some text
    Size: 37
    Message: Line3 - some text, limit here
    Line4 - some text
    Size: 48
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search