繁体   English   中英

为什么将 html 代码打印为字符串会在 python 中给出十六进制数字为 output?

[英]Why does printing html code as a string give hexadecimal numbers as output in python?

我写了一个 Python 代码来修改我的 html 内容。 但是在再次将其写入 html 文件时,我得到了奇怪的十六进制数字

import re

search="www.abc.com"

description="blah blah"

f = open('myhtml.html','r+')
content = f.read()
exp_keyword = re.compile(r'\.(\S+)\.')
reducedSearch = exp_keyword.findall(search)[0]

regexLink = re.compile(reducedSearch+r'\.'+r'.+'+'</a>',re.DOTALL)
matchregexLink = regexLink.search(content)
endOfMatch = matchregexLink.span()[1]   

#slice the string
s1 = content[:endOfMatch]
s2=content[endOfMatch:]

content = s1+description+s2
print(content)
f.truncate(0)
f.write(content)

 <html> <head> </head> <body> <div id="phy"> <p> ett </p> <div class="links"> <ul> <a href="www.abcd.com"> Link </a> <a href="www.abc.com"> Link </a> </ul> </div> </div> </body> </html>

0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 003c 6874 6d6c 3e0a
203c 6865 6164 3e0a 203c 2f68 6561 643e
0a20 3c62 6f64 793e 0a20 203c 6469 7620
6964 3d22 7068 7922 3e0a 2020 203c 703e
0a20 2020 2065 7474 0a20 2020 3c2f 703e
0a20 2020 3c64 6976 2063 6c61 7373 3d22
6c69 6e6b 7322 3e0a 2020 2020 3c75 6c3e
0a20 2020 2020 3c61 2068 7265 663d 2277
7777 2e61 6263 642e 636f 6d22 3e0a 2020
2020 2020 4c69 6e6b 0a20 2020 2020 3c2f
613e 0a20 2020 2020 3c61 2068 7265 663d
2277 7777 2e61 6263 2e63 6f6d 223e 0a20
2020 2020 204c 696e 6b0a 2020 2020 203c
2f61 3e62 6c61 6820 626c 6168 0a20 2020
203c 2f75 6c3e 0a20 2020 3c2f 6469 763e
0a20 203c 2f64 6976 3e0a 203c 2f62 6f64
793e 0a3c 2f68 746d 6c3e 0a

这些奇怪的十六进制数字就是我得到的 output。 但是,当我在代码中打印content时,它会给出正确的答案。 为什么这样? 我的预期答案是在包含 www.abc.com 链接的结束</a>标记之后写的blah blah

当你截断你的文件时,你实际上并没有回溯到文件中的 position 0 。 文件 position 仍然在原来的位置,现在已经超过了文件的末尾。

写入文件会将文本写入旧文件 position,将之前的所有内容留空。

十六进制不是由您发布的代码中的任何内容引起的。 您已经在一个工具中打开了该文件,该工具向您显示了字节的原始十六进制值。 由于所有 null 字节,此工具可能会这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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