-2

I've got a txt file(answer.txt), and I read all the lines into a list, one line is one element. And this lines look like:

'ABC3 ASLS43'

and I'd like to cut it like:

'ABC3'
'ASLS43'

Do you have any idea about it? I think It has a simple answer, but I'm a beginner, and I couldn't find anything 'bout it.

The code:

person=[]
with open('answer.txt', 'r') as v:
    ps=sum(1 for line in open('answer.txt'))
    print(ps)
    for i in range(0, ps):
        person.append(v.readline().strip()) #read line by line 
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

1

You can use the split() function. Try:

your_string.split()

Marcus Vinicius Melo
  • 1,118
  • 16
  • 23
1

You can use split() to split the string on spaces, and change append() for extend() which will append each element in the provided list.

person=[]
with open('answer.txt', 'r') as v:
    line = v.readline()
    while line:
        person.extend(line.strip().split())
        line = v.readline()
Jim Wright
  • 5,905
  • 1
  • 15
  • 34
  • With this, the list will look like: person=[['ABC3 ASLS43'], /.../], but I would like it like: person=[ABC3, ASLS43] – Ádám Papp Jan 15 '18 at 15:56
  • No, it will look like `person=['ABC3','ASLS43',...]`. I am using `split()` which returns a list (splits the string at the space), and `extend()` takes a list and adds each element to `person`. – Jim Wright Jan 15 '18 at 15:58
  • You are looping through the file twice though. You do not have to do that just to count the lines. – Ma0 Jan 15 '18 at 16:11
  • I used OP's code, but updated the array modification. My answer relates to the last line in this sample. I will update. – Jim Wright Jan 15 '18 at 17:30