Home > Net >  How to split a string in equal chunks at certain character in Python?
How to split a string in equal chunks at certain character in Python?

Time:05-02

So there is a string of values separated by \n. for example: "link1\nlink2\nlink3\nlink4\n" 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.

CodePudding user response:

You can use .split() and list comprehension:

a = "link1\nlink2\nlink3\nlink4\n"
b = a.split('\n')
[i for i in b if len(i)<4050 and i]

Output:

['link1', 'link2', 'link3', 'link4']

CodePudding user response:

You can use textwrap.wrap:

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

example:

s = "link1\nlink2\nlink3\nlink4\n"*1000

# get chunks
chunks = textwrap.wrap(s, width=4050)

# get size
list(map(len, chunks))
#[4049, 4049, 4049, 4049, 4049, 3749]
  • Related