Exercise 60

Write a Python program that defines a function replace_spaces_with_hyphen() which takes a string s as input and returns a new string with all spaces replaced with hyphens ("-") without using the replace() method. Exemple if s = "Python is object oriented programming language" , the function must returns: "Python-is-object-oriented-programming-language".


def replace_spaces_with_hyphens(s):
    Replaces spaces in a string with hyphens.

    s (str): The input string.

    str: The modified string with hyphens instead of spaces.
    # Create an empty string to store the modified string
    modified_string = ""

    # Iterate over each character in the input string
    for char in s:
        # If the character is a space, replace it with a hyphen
        if char == " ":
            modified_string += "-"
            modified_string += char

    return modified_string

s = "Python is object oriented programming language"
modified_s = replace_spaces_with_hyphens(s)
# Output: Python-is-object-oriented-programming-language

You can call this function with the input string "Python is object oriented programming language" to get the desired output: "Python-is-object-oriented-programming-language"


Younes Derfoufi

One thought on “Solution Exercise 60: replace the space with hyphen in python”

Leave a Reply