我從 fasta 檔案中創建了序列名稱和序列的串列。有人知道如何從序列名稱串列中洗掉“>”字符嗎?我嘗試過使用剝離、替換、映射。該串列提供以下輸出:
>chrI
>chrII
>chrIII
它應該在哪里:
chrI
chrII
chrIII
fp = open(r'demo_fasta_file_2022.fas', 'r')
def read_fasta(fp):
sequence_names, sequences = None, []
for line in fp:
line = line.rstrip()
if line.startswith(">"):
if sequence_names: yield (sequence_names, ''.join(sequences))
sequence_names, sequences = line, []
else:
sequences.append(line)
if sequence_names: yield (sequence_names, ''.join(sequences))
with open('demo_fasta_file_2022.fas') as fp:
for sequence_names, sequences in read_fasta(fp):
print(sequence_names)
uj5u.com熱心網友回復:
這個程序稱為字串切片。有很多方法可以做到這一點。這可能會有所幫助:https ://www.w3schools.com/python/gloss_python_string_slice.asp
uj5u.com熱心網友回復:
只需切片:
print(line[1:])
如果您不確定是否存在“>”,請使用:
if line.startswith(">"):
print(line[1:])
else:
print(line)
uj5u.com熱心網友回復:
您也可以使用正則運算式,它比line[1:]
import re
# ...
line = re.sub(r'^>', '', line, flags=re.MULTILINE)
哪里^是行首的符號,函式簽名是re.sub(REGEX, REPLACE_WITH, INPUTSTRING).
re.MULTILINE允許您使用^and$作為行的開始/結束。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441605.html
上一篇:如何將其轉換為串列理解
下一篇:瞄準由豎線分隔的單詞Python
