Python将字符串中的'\0'替换为nu

2024-09-27 09:33:10 发布

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

我现在面临一个奇怪的问题。 我想把字符串中的'\0'替换为'null',在许多论坛上阅读,总是看到相同的答案:

text_it = "request on port 21 that begins with many '\0' characters, 
preventing the affected router"
text_it.replace('\0', 'null')

或者

^{pr2}$

当我现在打印字符串时,我得到以下结果:

"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]

知道替换功能为什么不起作用吗?在


Tags: the字符串textthatonportrequestwith
2条回答

字符串是不可变的,因此不能通过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

在一行中:

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

相关问题 更多 >

    热门问题