Python Workout 05: Joining Strings

Level of Difficulty:

Objective: This workout provides practice in creating functions that will join a list of strings.

Problem: Create a function that takes a list of strings as input. Join each string in the list to create and return one complete string. Each word should have a space between them.

Examples:

join_strings(["Hello", "how", "are", "you?"]) -> "Hello how are you?"

join_strings(["What's", "your", "name?"]) -> "What's your name?"

Submission

Simply post your code and a screenshot of your results.

Please format your Python code and blur it or place it in a hidden section.

This workout will be released on Thursday April 13, 2023, and the author’s solution will be posted on Wednesday April 19, 2023.

def join_string(val):
    return " ".join(val)


print(join_string(["Hello", "how", "are", "you?"]))
1 Like

Great job @AntrikshSharma

I forgot to mention to avoid using the join method, but here is an answer.

def join_strings(string_list):
    """
    This function takes a list of strings as input and joins them to create one complete string without using .join().

    # Initialize an empty string to hold the result
    result = ""
    
    # Loop through each string in the list
    for string in string_list:
        # Add the current string to the result string, followed by a space
        result += string + " "
    
    # Remove the trailing space at the end of the result string and return it
    return result[:-1]

’ '.join([“Hello”, “how”, “are”, “you?”])

Without using the join() method, you can iterate over the list of strings and concatenate them manually using the + operator.

def join_strings(str_list):
    result = ""
    for i in range(len(str_list)):
        result += str_list[i]
        if i < len(str_list) - 1:
            result += " "
    return result

I love using Chatgpt to get explainers

EDNA AI also give you some great help

I definitely think getting AI assistance here to totally legitimate. This is the future of data science no doubt about it