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".
Solution
def replace_spaces_with_hyphens(s):
"""
Replaces spaces in a string with hyphens.
Args:
s (str): The input string.
Returns:
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 += "-"
else:
modified_string += char
return modified_string
s = "Python is object oriented programming language"
modified_s = replace_spaces_with_hyphens(s)
print(modified_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
CRMEF OUJDA
[…] Exercise 60 || Solution […]