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

0 votes

I use the following code segment to read a file in python:

with open ("data.txt", "r") as myfile:
    data=myfile.readlines()

Input file is:

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN
GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

and when I print data I get

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

As I see data is in list form. How do I make it string? And also how do I remove the "\n", "[", and "]" characters from it?

Dec 23, 2020 in Python by Roshni
• 10,480 points
654 views

1 answer to this question.

0 votes

You could use:

with open('data.txt', 'r') as file:
    data = file.read().replace('\n', '')
answered Dec 23, 2020 by Gitika
• 65,770 points

Related Questions In Python

0 votes
1 answer

Is it possible to read a text file into a string variable and then scrap the newlines?

This can be done easily in Python. ...READ MORE

answered Aug 7, 2019 in Python by Arvind
• 3,050 points
1,731 views
0 votes
1 answer

How to create and read from a temporary file in Python?

Hi, there is a very simple solution ...READ MORE

answered Jan 29, 2019 in Python by Nymeria
• 3,560 points
2,048 views
0 votes
1 answer

How to read data from a text file using Python?

Refer to the below example where the ...READ MORE

answered May 13, 2019 in Python by Sushma
1,509 views
0 votes
0 answers
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,069 views
0 votes
3 answers

How to distinguish between a variable and an identifier?

An identifier actually identifies something, it's not the thing ...READ MORE

answered Dec 16, 2020 in Python by Rajiv
• 8,870 points
65,080 views
0 votes
1 answer

How to transform a Python string into a list?

Hi, @Roshni, You can use Python <split()> function ...READ MORE

answered Jun 26, 2020 in Python by Gitika
• 65,770 points
667 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP