Skip to main content
 首页 » 编程设计

python之如何将字符串分成多行单个字符

2025年05月04日12grandyang

我不确定这个问题的标题是否合适,所以欢迎大家编辑。谢谢!

我的问题是,如果我有一串蛋白质序列:

seq='MIGQFGL'

我怎样才能把它转换成这样的:

MET 1 
ILE 2 
GLY 3 
GLN 4 
PHE 5 
GLY 6 
LEU 7 

这是我试过的:

f= open("protein.seq", "w") 
seq = 'MIGQFGL' 
 
d = {'C': 'CYS', 'D': 'ASP', 'S': 'SER', 'Q': 'GLN', 'K': 'LYS', 
 'I': 'ILE', 'P': 'PRO', 'T': 'THR', 'F': 'PHE', 'N': 'ASN', 
 'G': 'GLY', 'H': 'HIS', 'L': 'LEU', 'R': 'ARG', 'W': 'TRP', 
 'A': 'ALA', 'V':'VAL', 'E': 'GLU', 'Y': 'TYR', 'M': 'MET'} 
 
sp = list(seq) 
rep = '\n'.join(d.get(e,e) for e in sp) #to replace the items in list 'sp' with corresponding dictionary values 
 
no = list(range(1,8)) 
n = '\n'.join(str(x) for x in no) 
 
line = "{}\t{}\n".format(rep,n) 
f.write(line) 

但这就是我得到的:

MET 
ILE 
GLY 
GLN 
PHE 
GLY 
LEU 1 
2 
3 
4 
5 
6 
7 

因此,我更改了这一行:

line = "{}\t{}\n".format(rep,n)  

到:

line = "{}\t{}\n".format(zip(rep,n))  

但是我得到了:

Traceback (most recent call last): 
  File "protein.py", line 15, in <module> 
    line = "{}\t{}\n".format(zip(rep,n)) 
IndexError: tuple index out of range 

我做错了什么?提前致谢!

注意:我使用 Python 3。

请您参考如下方法:

使用 enumerate 会得到你想要的东西

rep = '\n'.join('{0} {1}'.format(d.get(s,s), i+1) for i, s in enumerate(seq)) 

此外,最好在文件处理时使用 with,因为它既安全又整洁。即

with open('proteins.seq', 'w') as f: 
    f.write(rep)