Samuel Langlais February 2016

Print next characters in line Python

I am looking to make a simple program that will find a character and then print the next 10 characters in the line. I have only been able to make it print out the whole line and the rest of line is useless. This is what i have for now.

f = open("Active Notship.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "P-" in line:
        print line

Answers


Samuel Langlais February 2016

Kevin was right. This is what I did.

f = open("Active Notship.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "P-" in line:
        print line[3:13]


tobias_k February 2016

Alternatively to find and slicing, you could also use a regular expression:

text = """some text
with many lines
some have a P- and some stuff behind it
like this: P- foo
and others don't
"""

import re
print(re.findall("(?<=P-).{1,10}", text))

Output: [' and some ', ' foo']

Post Status

Asked in February 2016
Viewed 3,882 times
Voted 5
Answered 2 times

Search




Leave an answer