Programming Problems · Q5
Q.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.
Uttarakhand UbseTextbookSubjective· 3mImportance★★★★★est
100% · 13/13 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Strings are immutable, so build a new string: copy every character, substituting '-' wherever the character is a space — or simply return sentence.replace(' ', '-').
Idea. The transformation is character-local: a space becomes a hyphen, everything else stays. Since Python strings cannot be modified in place, the function constructs a new string and returns it. Showing the explicit loop demonstrates the logic; replace() is the idiomatic shortcut.
def blankToHyphen(sentence):
"""Return the sentence with every blank replaced by a hyphen."""
newStr = ""
for ch in sentence:
if ch == ' ':
newStr += '-'
else:
newStr += ch
return newStr
# main program
s = input("Enter a sentence: ")
print("Modified sentence:", blankToHyphen(s))
Trace on the input "AB CD" (short example to show the mechanism):
| Step | ch | Action | newStr |
|---|---|---|---|
| 1 | A | copy | A |
| 2 | B | copy | AB |
| 3 | (space) | substitute '-' | AB- |
| 4 | C | copy | AB-C |
| 5 | D | copy | AB-CD |
Sample run
Enter a sentence: Python is fun to learn
Modified sentence: Python-is-fun-to-learn
``` …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.