简体   繁体   中英

Printing characters from a given sequence till a certain range only. How to do this in Python?

I have a file in which I have a sequence of characters. I want to read the second line of that file and want to read the characters of that line to a certain range only.

I tried this code, however, it is only printing specific characters from both lines. And not printing the range.

with open ("irumfas.fas", "r") as file:
    first_chars = [line[1] for line in file if not line.isspace()]
    print(first_chars)

Can anyone help in this regard? How can I give a range? Below is mentioned the sequence that I want to print.But I want to start printing the characters from the second line of the sequence till a certain range only.

IRUMSEQ ATTATAAAATTAAAATTATATCCAATGAATTCAATTAAATTAAATTAAAGAATTCAATAATATACCCCGGGGGGATCCAATTAAAAGCTAAAAAAAAAAAAAAAAAA

You can slice the line[1] in the file as you would slice a list.

You were very close:

end = 6 # number of characters
with open ("irumfas.fas", "r") as file:
    first_chars = [line[1][:end] for line in file if not line.isspace()]
    print(first_chars)

I think you want something like this:

with open("irumfas.fas", "r") as file:
    second_line = file.readlines()[1]
    print(second_line[0:9])

readlines() will give you a list of the lines -- which we index to get only the 2nd line. Your existing code will iterate over all the lines (which is not what you want).

As for extracting a certain range, you can use list slices to select the range of characters you want from that line -- in the example above, its the first 10.

The following approach can be used. Consider the file contains

RANDOMTEXTSAMPLE
SAMPLERANDOMTEXT
RANDOMSAMPLETEXT
with open('sampleText.txt') as sampleText:
    content = sampleText.read()
    content = content.split("\n")[1]
    content = content[:6]
    print(content)

Output will be

SAMPLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM