1

I would like to turn this (in a .txt file):

7316717653
1330624919

into this (in a Python list):

a_list = [7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9]

how do I do this? I've been looking everywhere, but nothing came close to what I intended to do

4
  • You can use this snippet list(text.replace('\n','')) Commented Nov 4, 2018 at 5:19
  • Show us what you tried. Commented Nov 4, 2018 at 5:21
  • @Xnkr ah, sorry about that, because I keep getting the wrong answer, I just delete all of the codes I've tried Commented Nov 4, 2018 at 5:31
  • You should read python.org tutorial first. You will get the answer yourself. Commented Nov 4, 2018 at 5:53

3 Answers 3

4
lst = []
with open('New Text Document.txt', 'r') as f: #open the file 
    lines = f.readlines() # combine lines of file in a list
    for item in lines: # iterate through items of  lines
        # iterate through items in each line and remove extra space after last item in the line using strip method
        for digit in item.strip(): 
            lst.append(int(digit)) # append digits in to the list and convert them to int

print(lst)
[7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9]
Sign up to request clarification or add additional context in comments.

Comments

0
with open('txtfile', 'r') as f:
    x = f.read()
print [y for y in list(x) if y != '\n']

Comments

0

Here's a complete solution:

num = '''7316717653
      1330624919'''
num = num.replace('\n', '')
# Write to a text file:
with open('filename.txt', 'w') as f:
    f.write(num)

# Now write to a Python List:
fd = open('filename.txt','rU')
chars = []
for line in fd:
    chars.extend(line)

Output is: [7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.