Add Length to Strings in Python

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"]
Code language: Python (python)

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(' ')]
Code language: Python (python)

Option 2:

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

Option 3:

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

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"])
Code language: Python (python)
Notify of
Inline Feedbacks
View all comments