Write a function that takes a sentence as an input parameter where each word in the sentence is separated by a space. The function should replace each blank with a hyphen and then return the modified sentence.
python def replaceBlank(sentence): # Replace each blank space with a hyphen modified_sentence = sentence.replace(' ', '-') return modified_sentence
Taking input from user
st = input("Enter a sentence: ") st1 = replaceBlank(st) print("The original sentence is:", st) print("The modified sentence is:", st1)
Output: Enter a sentence: Today is a Holiday The original sentence is: Today is a Holiday The modified sentence is: Today-is-a-Holiday
In this function, the replace() method is used to replace all occurrences of blank space (' ') with a hyphen ('-'). The function takes a sentence as an input parameter and returns the modified sentence with hyphens instead of spaces.
Explanation
The question requires replacing blank spaces with hyphens in a sentence. The textbook context shows the replace() method being used to replace characters in strings (e.g., str1.replace('o','') replaces all 'o' with ''). Similarly, the solution uses replace(' ', '-') to substitute each space with a hyphen. The function follows the pattern shown in Program 8-2 where a string is passed as a parameter and a modified string is returned.
Solution Steps
Step 1: Define a function replaceBlank() that takes a sentence as parameter.
Step 2: Use the replace() method to replace all blank spaces (' ') with hyphens ('-').
Step 3: Store the result in a variable and return the modified sentence.
Step 4: Take input from user and call the function to display the output.