0

I'm trying to turn a file into a list in Python that takes as elements each letters. The file 'file_input.txt' should look like this:

It is great

and the function should return: ['i','t','i','s','g','r','e','a','t']

I tried to do this:

file1 = open('file_input.txt', "r")
list_of_lists = []
for l in a_file1:
    s_line = l.strip() 
    l_list = s_line.split()
    list_of_lists = l_list
file1.close()

But it didn't work, also it should be case insensitive, can anyone help me please?

RMPR
  • 3,368
  • 4
  • 19
  • 31
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [ask] from the [tour]. "Teach me this basic language feature" is off-topic for Stack Overflow. You have to make an honest attempt at the solution, and then ask a _specific_ question about your implementation. Stack Overflow is not intended to replace existing tutorials and documentation. – TigerhawkT3 Apr 03 '21 at 00:41
  • This has a few good tips: https://stackoverflow.com/questions/113655/is-there-a-function-in-python-to-split-a-word-into-a-list – Davis Apr 03 '21 at 00:42
  • [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – RMPR Apr 03 '21 at 01:30

3 Answers3

1

You can use a context manager to open your file, that way you don't risk forgetting to close it:

list_of_lists = []
with open('file_input.txt') as file1:
    list_of_lists = [x.lower() for x in file1.read() if x != " " and x != "\n"]
RMPR
  • 3,368
  • 4
  • 19
  • 31
1

I would recommend you to do something like below

ans = []
with open("file_input.txt") as file:
    for line in file:
        ans.extend(list(line.replace(" ", "")))
print(ans) 
Sam Lee
  • 21
  • 2
0

You can use list() to turn a string into a list of characters, and str.replace() to remove any spaces from a string:

file = open('file_input.txt', 'r')
result = list(file.read().replace(' ',''))
file.close()

Btw, if you also want to remove newlines, just add .replace('\n', '') to the end of the result line, before the ')'

Also, if you want to make it case insensitive, just add .lower() to the end of the result line, before the ')'

pdemicheli
  • 19
  • 1