skip to Main Content

So there is a string of values separated by n.
for example:
"link1nlink2nlink3nlink4n"
I’m trying to send a message in telegram API but it has a length limit of 4050 characters. How can split the string into chunks of 4050 chars or less at n characters so it doesn’t mess up any links?
so I want the end result to be a list of strings containing 4050 characters or less, and the original list splitting points should be at "n" character.

2

Answers


  1. You can use .split() and list comprehension:

    a = "link1nlink2nlink3nlink4n"
    b = a.split('n')
    [i for i in b if len(i)<4050 and i]
    

    Output:

    ['link1', 'link2', 'link3', 'link4']
    
    Login or Signup to reply.
  2. You can use textwrap.wrap:

    import textwrap
    textwrap.wrap(s, width=4050)
    

    example:

    s = "link1nlink2nlink3nlink4n"*1000
    
    # get chunks
    chunks = textwrap.wrap(s, width=4050)
    
    # get size
    list(map(len, chunks))
    #[4049, 4049, 4049, 4049, 4049, 3749]
    

    Alternative to break on n exactly:

    def split(s, max_len=4050):
        out = []
        start = 0
        last_n = None
        for i, c in enumerate(s):
            if c == 'n':
                last_n = i
            if i-start>max_len or i+1 == len(s):
                out.append(s[start:last_n+1])
                start = last_n+1
        return out
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search