0

How to iterate over every line of a string in Python?

The title says it all. Maybe string.split('\n') and then iterate the resulting list?

6th May 2019, 1:36 PM
Dan Karnaukh
6 RĂ©ponses
+ 3
If text (var) contains a string with ‘\n’ and other line breakes and you want to get each line you can get it also with: for line in text.splitlines(): print(line) #————————— there is also a nice feature by adding True inside the round brackets in the method call. It keeps the separators. See samples: text = 'to be \nor not to be \u2028that is the question' lst = text.splitlines() # result: ['to be ', 'or not to be ', 'that is the question'] lst1 = text.splitlines(True) # result: ['to be \n', 'or not to be \u2028', 'that is the question']
6th May 2019, 3:55 PM
Lothar
Lothar - avatar
+ 5
for line in string.split('\n'):
6th May 2019, 1:56 PM
Anna
Anna - avatar
+ 1
Dan Karnaukh seems I misunderstood you, anyways Anna's got a good answer
6th May 2019, 2:00 PM
Dlite
Dlite - avatar
0
Would'nt that iterate over every character instead of every line?
6th May 2019, 1:45 PM
Dan Karnaukh
0
Thank you everyone.
6th May 2019, 7:48 PM
Dan Karnaukh
- 1
name = 'Dan Karnaukh' for character in name: print(character)
6th May 2019, 1:42 PM
Dlite
Dlite - avatar