I have a big text, I have split it into lines. Let's say the text is 100 lines I want to get whatever is between line 30 and line 60 How do I do that?
-
Via list indices: `lines[30:60]` – fsimonjetz Jun 28 '21 at 14:49
-
Please post a sample of your text. – Ram Jun 28 '21 at 14:52
3 Answers
With lists in python, you can chose what part of a list with the [x:y].
For example let's say you have a list
list = [0,
1,
2,
3,
4,
5]
If you only want the part of the list contained between 1 and 4 you can type
list[1:4]
and it will return you [1, 2, 3, 4]
.
Have a nice day.

- 129
- 6
If I'm got it right, your question is quite related to this: How to read a file line-by-line into a list?
You could do:
with open("file.txt") as file_in:
lines = []
for line in file_in:
lines.append(line)
or simply:
with open('file.txt') as f:
lines = f.readlines()
and work with the lines you would like to, according to index of lines created. Something like:
sub_text = lines[30:60]

- 181
- 2
- 14
If the lines are seperated by new lines, you can use the .split method to turn your long String into a list, and then get everything from index 29 to 59 using a for loop.
Here's an example:
seperatedText = longString.split("\\n")
for i in range 30:
print(seperatedText[i + 29])
Of course you can also put the output into a second list by using the .append method or whatever you want.
I hope I could help you, and I'd really appreciate an upvote or an approve for my reputation :)

- 45
- 1
- 6