Skip to content

Instantly share code, notes, and snippets.

@Elijas
Created July 8, 2020 04:17
Show Gist options
  • Save Elijas/f6c12c31f07a9db21a1971f0fe2f7d01 to your computer and use it in GitHub Desktop.
Save Elijas/f6c12c31f07a9db21a1971f0fe2f7d01 to your computer and use it in GitHub Desktop.
from typing import List
def split_message(input_msg: str, max_length: int, allocated_chars=None) -> List[str]:
allocated_chars_arg = allocated_chars
max_length_arg = max_length
if allocated_chars_arg is None:
allocated_chars = 6
assert max_length > 1 + allocated_chars
max_length -= allocated_chars
msgs = []
msg = ''
def add_msg(msg):
new_msg = msg.strip()
msgs.append(new_msg)
for word in input_msg.split():
if len(f'{msg} {word}') > max_length:
add_msg(msg)
msg = ''
msg = f'{msg} {word}'
add_msg(msg)
if len(msgs) > 1:
msgs = [f"{msg} ({i}/{len(msgs)})" for i, msg in enumerate(msgs, start=1)]
if len(msgs) >= 10 and allocated_chars_arg is None:
allocated_chars = 6 + 2 * len(str(len(msgs)))
return split_message(input_msg, max_length_arg, allocated_chars)
return msgs
if __name__ == '__main__':
print(split_message("Hi", 20))
print(split_message("Hi Hello Wonderful World", 20))
print(split_message("Hi Hello Wonderful World " * 20, 50))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment