Python Forum
Split string into 160-character chunks while adding text to each part
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Split string into 160-character chunks while adding text to each part
#1
HELP!
A company has hired you as a consultant to develop software that can be used for sending SMS to their end-users. Currently, the maximum number of characters possible for one message is 160. Some of the messages the company sends contain more than 160 characters and need to be broken up into smaller chunks.

The company has expressed concerns that when sending messages in different chunks there is no guarantee that the messages will be delivered to the end-user’s phone in order. To circumvent this problem, the company would like to add pagination to the end of the message to give proper context to the end-user if needed.

As an example, the following message has 212 characters:
As a reminder, you have an appointment with Dr. Smith tomorrow at 3:30 pm. If you are unable to make this appointment, please call our customer service line at least 1 hour before your scheduled appointment time.

The message should be sent in two chunks as such:
As a reminder, you have an appointment with Dr. Smith tomorrow at 3:30 pm. If you are unable to make this appointment, please call our customer service (1/2)
and
line at least 1 hour before your scheduled appointment time. (2/2)

Your task is to develop a function that takes in a string message and returns an array of string messages with pagination if needed. For this exercise, the maximum number of characters in the input message is 1440. Also, do not break words into syllables and hyphens.
Reply
#2
Please show what you have tried so far.
We're here to help, but not do the work for you.
Reply
#3
What have tried? Post your code in python tags, full traceback in error tags and ask specific questions. We are glad to help but we don't write code for you
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
Use a for loop
message = 'long message'
#Some predefined variables
for i in message:
    #code here
If i was able to do it with a for loop you can too
Reply
#5
well this is what i was trying to do:
SMS_LENGTH = 160
SUFFIX_TEMPLATE = ' - Part %d of %d'

def split_count(text)
  rest_length = len(text)
  count = 0
  while rest_length > 0
    count += 1
    rest_length -= payload_size(count)
  count

def render_suffix(i, count)
  format(SUFFIX_TEMPLATE, i, count)

def payload_size(nth)
	switcher ={
		1: SMS_LENGTH,
		2: SMS_LENGTH - 2 * render_suffix(nth, nth).size
	}
    func = switcher.get(nth, lambda: SMS_LENGTH - render_suffix(nth, nth).length - (is_power_of_10?(nth) ? nth - 1 : 0))
    print(func())


def is_power_of_10?(n)
  Math.log10(n) % 1 == 0
Reply
#6
Do you normally write Ruby?

In Python, functions return nothing unless you use the return keyword. Further, punctuation is not valid in a function name. So the first step to getting the code to work, is getting it to run without syntax errors.
Reply
#7
Maybe it doesn't sound like a difficult task but the rule about not breaking words in combination with the pagination and 1440 char limit makes it a bit complicated I think.

'''
Max length of the message is 1440, this would mean that the number of SMS will
not exceed 9 (because 1440/160 is 9) but that is not true.

After adding characters needed for pagination the total length of all messages
may exceed 1440 and occupy 10 SMS all together. This in turn will change
how many characters the pagination requires.
E.g. instead of (1/9) it could be (1/10) which takes 1 character more.

The task does not specify that the messages must be sent in the most efficient
way, therefore it will be assumed that each page symbol always occupies 7
characters instead of 6 or variable number.
'''

example_text = "As a reminder, you have an appointment with Dr. Smith tomorrow at 3:30 pm. If you are unable to make this appointment, please call our customer service line at least 1 hour before your scheduled appointment time."
example_text_2 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
example_text_3 = "Very short message without pagination."
example_text_4 = "A " * 719 + "BB" # text that has 1440 characters (with BB at the end to make sure it's properly sending the characters at the end)


def get_index_of_last_space_before_nth_char(text, n):
    '''Function that checks where to cut the message (it can't be just cut at
    160th char because it could cut mid-word).

    Notice that if the text message does not contain a space character then
    it just won't work. So it would be good idea to modify this function
    so it will return index of last of any 'whitespace' (e.g. tab, carriage
    return/new line) or punctuation (or both combined).'''
    return n - text[:n][::-1].index(' ')    

def get_string_messages(msg):
    '''Function that takes in a string message and returns
    an array of string messages with pagination if needed.'''
    if len(msg) <= 160:
        # No pagination is needed
        return [msg]
    else:
        # Pagination is needed
        single_str_max_len = 153 # 153 because 7 chars are reserved for page number

        string_messages = []

        while msg:
            if len(msg) <= single_str_max_len:
                # if it's the last message then don't bother about not breaking words
                msg_len = len(msg)
            else:
                # check where is the last space before end of the sms to avoid breaking words
                msg_len = get_index_of_last_space_before_nth_char(msg, single_str_max_len)
            
            # generate new SMS
            msg_content = msg[: msg_len]

            # append it to returned list
            string_messages.append(msg_content)

            # cut it out of the whole text
            msg = msg[msg_len:]

        # append pagination to each string message
        for i in range(0, len(string_messages)):
            string_messages[i] += f'({i+1}/{len(string_messages)})'
            
    return string_messages

def present_program_functionality():
    print("Example 1:")
    for i, sms in enumerate(get_string_messages(example_text)):
        print(f'SMS number {i+1}: {sms}')

    print("\n\nExample 2:")
    for i, sms in enumerate(get_string_messages(example_text_2)):
        print(f'SMS number {i+1}: {sms}')

    print("\n\nExample 3:")
    for i, sms in enumerate(get_string_messages(example_text_3)):
        print(f'SMS number {i+1}: {sms}')

    print("\n\nExample 4:")
    for i, sms in enumerate(get_string_messages(example_text_4)):
        print(f'SMS number {i+1}: {sms}')
        
present_program_functionality()
Output:
Example 1: SMS number 1: As a reminder, you have an appointment with Dr. Smith tomorrow at 3:30 pm. If you are unable to make this appointment, please call our customer service (1/2) SMS number 2: line at least 1 hour before your scheduled appointment time.(2/2) Example 2: SMS number 1: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, (1/3) SMS number 2: quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum (2/3) SMS number 3: dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.(3/3) Example 3: SMS number 1: Very short message without pagination. Example 4: SMS number 1: A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A (1/10) SMS number 2: A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A (2/10) SMS number 3: A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A (3/10) SMS number 4: A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A (4/10) SMS number 5: A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A (5/10) SMS number 6: A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A (6/10) SMS number 7: A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A (7/10) SMS number 8: A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A (8/10) SMS number 9: A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A (9/10) SMS number 10: A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A BB(10/10)
Reply
#8
This is the code I used.
message = 'As a reminder, you have an appointment with Dr. Smith tomorrow at 3:30 pm. If you are unable to make this appointment, please call our customer service line at least 1 hour before your scheduled appointment time.'

count = 0
num = 0
output = ('', '', '', '', '', '', '', '', '')

for i in message:
    count += 1
    if count < 161:
        outputStr = output[num] + i
        ouput[num] = outputStr
    else:
        num += 1
        outputStr = output[num] + i
        output[num] = outputStr
        count = 0

messsageNum = 0

for x in output:
    if x != '':
        messageNum += 1
        print(f'message number {messageNum} is {x} and has a length of {len(x) character}')
        print('')
Reply
#9
(Apr-30-2019, 06:15 PM)iambobbiekings Wrote: HELP!
A company has hired you as a consultant to develop software that can be used for sending SMS to their end-users. Currently, the maximum number of characters possible for one message is 160. Some of the messages the company sends contain more than 160 characters and need to be broken up into smaller chunks.

The company has expressed concerns that when sending messages in different chunks there is no guarantee that the messages will be delivered to the end-user’s phone in order. To circumvent this problem, the company would like to add pagination to the end of the message to give proper context to the end-user if needed.

As an example, the following message has 212 characters:
As a reminder, you have an appointment with Dr. Smith tomorrow at 3:30 pm. If you are unable to make this appointment, please call our customer service line at least 1 hour before your scheduled appointment time.

The message should be sent in two chunks as such:
As a reminder, you have an appointment with Dr. Smith tomorrow at 3:30 pm. If you are unable to make this appointment, please call our customer service (1/2)
and
line at least 1 hour before your scheduled appointment time. (2/2)

Your task is to develop a function that takes in a string message and returns an array of string messages with pagination if needed. For this exercise, the maximum number of characters in the input message is 1440. Also, do not break words into syllables and hyphens.
Reply
#10
Smile
Been more than a year since i posted this, bumped on it today and decided to share a perfect solution i worked on. Check it out on Github: https://github.com/arllence/sms-sender.git
Dance
nilamo likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Reading a text until matched string and print it as a single line cananb 1 2,017 Nov-29-2020, 01:38 PM
Last Post: DPaul
  Replacing a few characters of a specified character but not all of them from a string fatherted99 7 3,192 Aug-13-2020, 09:08 AM
Last Post: fatherted99
  Appending to a text string syno7878 10 4,217 May-03-2020, 10:05 AM
Last Post: snippsat
  Using an integer to manipulate a string/text variable rexyboy2121 1 1,732 Apr-22-2020, 01:37 AM
Last Post: michael1789
  Adding string numbers, while loop and exit without input. Jose 11 7,460 Apr-15-2020, 08:34 AM
Last Post: Jose
  Trying to extract Only the capitol letters from a string of text Jaethan 2 2,168 Feb-27-2020, 11:19 PM
Last Post: Marbelous
  How to change part of the value string in Python Dictionary? sbabu 11 3,895 Feb-12-2020, 02:25 AM
Last Post: sbabu
  Tab character in a string prints 8 spaces hecresper 6 20,513 Aug-27-2019, 02:38 PM
Last Post: snippsat
  Split String lekuru01 6 3,458 Mar-19-2019, 10:42 AM
Last Post: lekuru01
  Finding and storing all string with character A at middle position Pippi 2 2,670 Jan-20-2019, 08:23 AM
Last Post: Pippi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020