Python3.4字典输出不同于Python2.7

2024-04-27 21:21:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是在学习Python,所以如果我完全遗漏了一些东西,我不会感到惊讶。这是一个BAM格式的序列文件,通过从pysam获取读取。在python3.4中的python2.7中所有的东西都可以工作这段代码

consensus = readDict[dictTag][6][maxCig][2:]
print(consensus)

从python2.7输出这个[b'GATC']而不是所需的['GATC']

这种行为的根源是什么?他们有什么解决办法吗?你知道吗


Tags: 文件代码格式序列printbamconsensus根源
1条回答
网友
1楼 · 发布于 2024-04-27 21:21:49

在python2.x中,'GATC'是字节字符串,u'GATC'是Unicode字符串。你知道吗

在python3.x中,'GATC'是Unicode字符串,b'GATC'是字节字符串。你知道吗

所以在这两种情况下得到的结果(字节字符串)是相同的。你知道吗

您可以在Python 3.x中将字节字符串解码为Unicode,以获得所需的结果:

>>> s = b'GATC'
>>> s
b'GATC'
>>> s.decode() # default UTF-8 decoding.
'GATC'
>>> s.decode('ascii')
'GATC'

编辑

根据OP下面的评论,这里是另一个例子:

>>> s=[b'GATC',b'CTAG'] # A list of byte strings
>>> s
[b'GATC', b'CTAG']
>>> s = [t.decode() for t in s] # decoding the list to Unicode
>>> s
['GATC', 'CTAG']
>>> for t in s:    # iterating over the strings and characters
...  for c in t:
...   print(t,c)
...
GATC G
GATC A
GATC T
GATC C
CTAG C
CTAG T
CTAG A
CTAG G

如果跳过解码,会得到什么:

>>> s=[b'GATC',b'CTAG']
>>> for t in s:
...  for c in t:
...   print(t,c)
...
b'GATC' 71    # displays as byte strings and byte values (71 == ASCII 'G', etc.)
b'GATC' 65
b'GATC' 84
b'GATC' 67
b'CTAG' 67
b'CTAG' 84
b'CTAG' 65
b'CTAG' 71

相关问题 更多 >