Add Size to Strings in Python


The problem

What if we want the size of the phrases separated by an area to be added on the finish of that very same phrase and have it returned as an array?

add_length('apple ban') => ["apple 5", "ban 3"]
add_length('you'll win') => ["you 3", "will 4", "win 3"]

Your activity is to write down a perform that takes a String and returns an Array/listing with the size of every phrase added to every component.

Be aware: String could have not less than one component; phrases will all the time be separated by an area.

The answer in Python code

Possibility 1:

def add_length(str_):
    return [str(x)+' '+str(len(x)) for x in str_.split(' ')]

Possibility 2:

def add_length(string):
    return ["{} {}".format(word, len(word)) for word in string.split(" ")]

Possibility 3:

def add_length(str_):
    reply = []
    for phrase in str_.break up():
        reply.append(phrase + ' ' + str(len(phrase)))
    return reply

Take a look at instances to validate our answer

import check
from answer import add_length

@check.describe("Mounted Assessments")
def basic_tests():
    check.assert_equals(add_length('apple ban'),["apple 5", "ban 3"])
    check.assert_equals(add_length('you'll win'),["you 3", "will 4", "win 3"])
    check.assert_equals(add_length('you'),["you 3"])
    check.assert_equals(add_length('y'),["y 1"])


Leave a Reply