Categories
Python Answers

How to read a text file into a string variable and strip newlines with Python?

Spread the love

Sometimes, we want to read a text file into a string variable and strip newlines with Python.

In this article, we’ll look at how to read a text file into a string variable and strip newlines with Python.

How to read a text file into a string variable and strip newlines with Python?

To read a text file into a string variable and strip newlines with Python, we can use the replace method.

For instance, we write

with open('data.txt', 'r') as file:
    data = file.read().replace('\n', '')

to open the data.txt file with open.

And then we call file.read to read the file into a string.

Then we call the string replace method to replace all new line characters with empty strings.

Conclusion

To read a text file into a string variable and strip newlines with Python, we can use the replace method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *