A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

Read text file into a variable and replace all newlines with space using python programming
Q:

Read text file into a variable and replace all newlines with space using python programming

0

Read text file into a variable and replace all newlines with space

Given: Assume you have a following text file (sample.txt).

Line1
line2
line3
line4
line5

Expected Output:

Line1 line2 line3 line4 line5

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Hint:

  • First, read a text file.
  • Next, use string replace() function to replace all newlines (\n) with space (' ').

Solution:

  • First, open the file in a read mode
  • Next, read all content from a file using the read() function and assign it to a variable.
  • Next, use string replace() function to replace all newlines (\n) with space (' ').
  • Display final string
with open('sample.txt', 'r') as file:
    data = file.read().replace('\n', ' ')
    print(data)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now