我目前面临一个奇怪的问题。 我想用'null'替换字符串中的'\ 0',并通读许多论坛,总是看到相同的答案:
text_it = "request on port 21 that begins with many '\0' characters,
preventing the affected router"
text_it.replace('\0', 'null')
或
text_it.replace('\x00', 'null')
当我现在打印字符串时,得到以下结果:
"request on port 21 that begins with many '\0' characters, preventing the
affected router"
什么都没发生。
因此,我使用了这种方法,它奏效了,但对于这么小的更改似乎太费力了:
text_it = text_it.split('\0')
text_it = text_it[0] + 'null' + text_it[1]
有人知道为什么替换功能不起作用吗?
答案 0 :(得分:1)
一行中
text_it = text_it.replace('\0', 'null').replace('\x00', 'null')
答案 1 :(得分:0)
字符串是不可变的,因此无法通过replace()
方法进行修改。但是此方法返回预期的输出,因此您可以将此返回值分配给text_it
。这是(简单的)解决方案:
text_it = "request on port 21 that begins with many '\0' characters, preventing the affected router"
text_it = text_it.replace('\0', 'null')
print(text_it)
# request on port 21 that begins with many 'null' characters, preventing the affected router