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?
6 Respostas
+ 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']
+ 5
for line in string.split('\n'):
+ 1
Dan Karnaukh seems I misunderstood you, anyways Anna's got a good answer
0
Would'nt that iterate over every character instead of every line?
0
Thank you everyone.
- 1
name = 'Dan Karnaukh'
for character in name:
print(character)