Write a program to replace all spaces from text with - (dash)from the file podar.txt.
Question
Write a program to replace all spaces from text with - (dash) from the file podar.txt
.
Solution
Sure, here is a simple Python program that reads a file, replaces all spaces with dashes, and writes the result back to the file.
# Open the file in read mode and read its content
with open('podar.txt', 'r') as file:
content = file.read()
# Replace all spaces with dashes
content = content.replace(' ', '-')
# Open the file in write mode and write the modified content
with open('podar.txt', 'w') as file:
file.write(content)
This program works as follows:
- It opens the file
podar.txt
in read mode and reads its content into the variablecontent
. - It uses the
replace
method of the string class to replace all spaces incontent
with dashes. The result is stored back incontent
. - It opens the file
podar.txt
again, this time in write mode, and writes the modified content back to the file. This overwrites the original content of the file.
Please replace 'podar.txt' with your actual file path and name.
Similar Questions
Create a text file "podar.txt" in python and ask the user towrite a single line of text by user input
Write a Python program to replace whitespaces with an underscore and vice versa.
Which method can be used to remove any whitespace from both the beginning and the end of a string?
Fill in the blank: To remove leading, trailing, and repeated spaces when cleaning data, use the _____ function. 1 pointCLIPCLEANTRIMEXTRACT
What command can be used to edit a text file on a Linux server?Question 2Select one:a.lsb.catc.nanod.edit
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.