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.