gpt4 book ai didi

python - 为什么这个字符串没有变成大写?

转载 作者:行者123 更新时间:2023-12-01 04:38:52 30 4
gpt4 key购买 nike

所以我有一个氨基酸文件,我正在尝试读取mdvfmkglskakegvvaaaektkqgvaeaagktkegvlyvgsktkegvvhgvatvaektk
eqvtnvggavvtgvtavaqktvegagsiaaatgfvkkdqlgkneegapqegiledmpvdp
dneayempseegyqdyepea

我有一个称为氨基酸的大写字母列表。问题是我无法读取序列,因为字母是小写的。我一直在尝试将其变为大写。读取文件没有任何问题,我以为我已经成功地将其内容转换为字符串(但也许我没有?)。

aminoacids = ['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y']
content1 = fh.readline() #first line, which is not the sequence
#print content1
charline1 = len(content1)-1 #number of characters in the first line
#print charline1
contentall = fh.readlines() #each line is converted into a string and put into a list
#print contentall
numlines = len(contentall) #number of elements in list = number of lines, not the first one
#print numlines
contentjoined = ''.join(contentall) #list elements are combined, but this includes new lines as characters
contentjoined = contentjoined.translate(None, "\n")
contentjoined = contentjoined.translate(None,''.join([i for i in contentjoined if i not in aminoacids]))
contentjoined = contentjoined.upper()
print contentjoined
numaa = len(contentjoined)
print numaa #this shouldn't be zero but it is

为什么这不起作用?我能做什么来修复它?我现在处于 with 状态...以前这不是问题,但现在是吗? Numaa 是 0,而它不应该是 0。我意识到我可以将小写字母添加到我的列表中,但应该有一种更“Pythonic”的方法来解决这个问题。

最佳答案

是否是因为在检查aminoacids中的字符串后将字符串变为大写?尝试将 contentjoined = contentjoined.upper() 向上移动一两行。

当您检查aminoacids时,您为str.translate提供了一个完全小写的字符串,因此它与字符串不匹配。它最终看起来像这样:

>>> c = contentjoined.translate(None,''.join([i for i in contentjoined if i not in aminoacids]))
>>> c
''

如果您首先调用 upper,您将把一个大写字符串与一个大写字符串列表进行比较,这样您实际上就会得到匹配项。它看起来像这样:

>>> contentjoined = contentjoined.upper()
>>> c = contentjoined.translate(None,''.join([i for i in contentjoined if i not in aminoacids]))
>>> c
'MDVFMKGLSKAKEGVVAAAEKTKQGVAEAAGKTKEGVLYVGSKTKEGVVHGVATVAEKTKEQVTNVGGAVVTGVTAVAQKTVEGAGSIAAATGFVKKDQLGKNEEGAPQEGILEDMPVDPDNEAYEMPSEEGYQDYEPEA'

如果你想保留字符串为小写字母,你可以只与大写字母进行比较并保留小写字母。看起来像这样:

>>> c = contentjoined.translate(None,''.join([i for i in contentjoined.upper() if i not in aminoacids]))
>>> c
'mdvfmkglskakegvvaaaektkqgvaeaagktkegvlyvgsktkegvvhgvatvaektkeqvtnvggavvtgvtavaqktvegagsiaaatgfvkkdqlgkneegapqegiledmpvdpdneayempseegyqdyepea'

关于python - 为什么这个字符串没有变成大写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31191820/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com