Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python替换'\0';字符串中包含null_Python_Replace_Null Terminated - Fatal编程技术网

Python替换'\0';字符串中包含null

Python替换'\0';字符串中包含null,python,replace,null-terminated,Python,Replace,Null Terminated,我现在面临一个奇怪的问题。 我想将字符串中的“\0”替换为“null”,并在许多论坛中阅读,始终看到相同的答案: text_it = "request on port 21 that begins with many '\0' characters, preventing the affected router" text_it.replace('\0', 'null') 或 现在打印字符串时,得到以下结果: "request on port 21 that begins with many

我现在面临一个奇怪的问题。 我想将字符串中的“\0”替换为“null”,并在许多论坛中阅读,始终看到相同的答案:

text_it = "request on port 21 that begins with many '\0' characters, 
preventing the affected router"
text_it.replace('\0', '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]

知道为什么replace函数不起作用吗?

字符串是不可变的,因此不能通过
replace()
方法修改它们。但是此方法返回预期的输出,因此您可以将此返回值分配给
text\u 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
在一行中:

text_it = text_it.replace('\0', 'null').replace('\x00', 'null')

text\u it=text\u it.replace('\0',null')
?它可以me@Rakesh当然有时候我就是看不到显而易见的东西。谢谢@别忘了选择你喜欢的答案。
text_it = text_it.replace('\0', 'null').replace('\x00', 'null')