1

I'm currently facing a strange problem. I want to replace the '\0' in strings with 'null' and read through many forums and always saw the same answer:

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

or

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

When I now print the string, I get the following result:

"request on port 21 that begins with many '\0' characters, preventing the 
affected router"

Nothing happened.

So I used this method and it worked but it seems to be too much effort for such a small change:

text_it = text_it.split('\0')
text_it = text_it[0] + 'null' + text_it[1]

Any idea why the replace function didn't work?

1
  • 2
    text_it = text_it.replace('\0', 'null') ? Commented Aug 10, 2018 at 8:24

2 Answers 2

3

In one single line:

text_it = text_it.replace('\0', 'null').replace('\x00', 'null')
Sign up to request clarification or add additional context in comments.

Comments

0

Strings are immutable, so they can not be modified through the replace() method. But this method returns the expected output, so you can assign this returned value to text_it. Here is the (simple) solution:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.