हिंदी

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

Advertisements
Advertisements

प्रश्न

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.

संक्षेप में उत्तर
Advertisements

उत्तर

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.
shaalaa.com
String Handling in Python
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 8: Strings - Exercise [पृष्ठ १८८]

APPEARS IN

एनसीईआरटी Computer Science [English] Class 11
अध्याय 8 Strings
Exercise | Q 5. | पृष्ठ १८८
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×