CameraIcon
CameraIcon
SearchIcon
MyQuestionIcon
MyQuestionIcon
3
You visited us 3 times! Enjoying our articles? Unlock Full Access!
Question

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.

Open in App
Solution


Program:
#replaceChar function to replace space with hyphen
def replaceChar(string):
return string.replace(' ','-')

userInput = input("Enter a sentence: ")

#Calling the replaceChar function to replace space with hyphen
result = replaceChar(userInput)

#Printing the modified sentence
print("The new sentence is:",result)


OUTPUT:
Enter a sentence: Python has several built-in functions that allow us to work with strings.
The new sentence is: Python-has-several-built-in-functions-that-allow-us-to-work-with-strings.



The same task can also be accomplished without using the string.replace() function. The program for the same can be written as :
Program:
#replaceChar function to replace space with hyphen
def replaceChar(string):
newString = ''
#Looping through each character of string
for a in string:
#if char is space, replace it with hyphen
if a == ' ':
newString += '-'
#else leave the character as it is
else:
newString += a
return newString

userInput = input("Enter a sentence: ")

#Calling the replaceChar function to replace space with hyphen
result = replaceChar(userInput)

#Printing the modified sentence
print("The new sentence is:",result)


OUTPUT:
Enter a sentence: Python has several built-in functions that allow us to work with strings.
The new sentence is: Python-has-several-built-in-functions-that-allow-us-to-work-with-strings.

flag
Suggest Corrections
thumbs-up
0
Join BYJU'S Learning Program
similar_icon
Related Videos
thumbnail
lock
The Relationship between the Houses
CIVICS
Watch in App
Join BYJU'S Learning Program
CrossIcon