Add Length to Strings in Python

0 min read 172 words

The challenge

What if we need the length of the words separated by a space to be added at the end of that same word and have it returned as an array?

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

Your task is to write a function that takes a String and returns an Array/list with the length of each word added to each element.

Note: String will have at least one element; words will always be separated by a space.

The solution in Python code

Option 1:

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

Option 2:

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

Option 3:

def add_length(str_):
    answer = []
    for word in str_.split():
        answer.append(word + ' ' + str(len(word)))
    return answer

Test cases to validate our solution

import test
from solution import add_length

@test.describe("Fixed Tests")
def basic_tests():
    test.assert_equals(add_length('apple ban'),["apple 5", "ban 3"])
    test.assert_equals(add_length('you will win'),["you 3", "will 4", "win 3"])
    test.assert_equals(add_length('you'),["you 3"])
    test.assert_equals(add_length('y'),["y 1"])
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts