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:

Input file is:


and when I print data I get


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

1 answer to this question.

0 votes

You could use:

with open('data.txt', 'r') as file:
    data ='\n', '')
answered Dec 23, 2020 by Gitika
• 65,970 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,020 points
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,540 points
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
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 2,485 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,810 points
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,910 points
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,970 points