SurlyJake Blog

View String Including Special Characters Like Newlines in Python

| Comments

After spending a frustrating hour or two trying to format a string, i stumbled on python’s repr() funcion. repr() allows you to inspect a string object when you’re troubleshooting your code. For example:

I was trying to understand a string that was shown in the terminal like this:

print mystring




Node - 192.168.1.104
ERROR:
Description = Generic failure

Seems pretty simple to remove the extra newline characters right? no. doing a string.replace(“\n”, “ ”) did not fix it, but actually mangled the string. So here comes repr() to the rescue…

print repr(mystring)




'Node - 192.168.1.104\r\r\nERROR:\r\r\nDescription = Generic failure\r\r\n'

\r\r\n… i’ve never heard of it before, but knowing that it’s there, i could easily change my replace to:

print mystring.replace("\r\r\n", " ")




Node - 192.168.1.104 ERROR: Description = Generic failure 

Comments