Sunday, April 14, 2024
HomeSoftware EngineeringAdd Size to Strings in Python

Add Size to Strings in Python

The problem

What if we’d like 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 job is to jot down a perform that takes a String and returns an Array/checklist with the size of every phrase added to every factor.

Word: String can have at the very least one factor; phrases will all the time be separated by an area.

The answer in Python code

Choice 1:

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

Choice 2:

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

Choice 3:

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

Take a look at instances to validate our answer

import take a look at
from answer import add_length

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


Please enter your comment!
Please enter your name here

Most Popular

Recent Comments