New line as a separator in python

Viewed 233

I have following code to get lines with string i need

import pyscp
f = open("base.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "смерть" in line: 
        for l in searchlines[i: i+3]: print(l)

For example, i am searching for "смерть" It gives me following

SCP-1056-RU-V - Жизнь и смерть

SCP-1056-RU - Творческие метания

SCP-2061 - Целая местная семья подавилась насмерть одним калькулятором

SCP-2062 - Кронекер

SCP-2668 - Идущие на смерть приветствуют тебя!

SCP-2669 - Кебтеул 1

SCP-510 - Мягкая смерть

SCP-5115 - Не от мира сего

SСP-3984 - Потыкай в смерть палочкой

SСP-4220 - Темная сторона Луны

I want to make list like this [scp-xxx--ejdj, scp-xxxx-jddj...] So i need to use new line as a separator, how can i do that? linesplite doesn't work here.

1 Answers

You can use str.split() and firs value is your SCP-xxx variable:

f = open("your_file.txt", "r")
searchlines = [line.strip() for line in f.readlines() if line.strip()] # <-- skip empty lines
f.close()

out = []
for i, line in enumerate(searchlines):
    if "смерть" in line:
        for l in searchlines[i : i + 3]:
            out.append(l.split(maxsplit=1)[0])  # <-- add to out the first value

print(out)

Prints:

['SCP-1056-RU-V', 'SCP-1056-RU', 'SCP-2061', 'SCP-2061', 'SCP-2062', 'SCP-2668', 'SCP-2668', 'SCP-2669', 'SCP-510', 'SCP-510', 'SCP-5115', 'SСP-3984', 'SСP-3984', 'SСP-4220']
Related