Python strings are the \n Devil!

For anyone who has taken any of my workshops or seen my Python talks, you know I am not a big fan of how Python handles strings in general. Today as I was working on a project it occurred to me that there is probably a “best practice” that I need to get into for fixing a really annoying and VERY common issue. Let’s say you are trying to pass a string with a variable in it:

sql_cmd = "UPDATE txmanager.portal SET context_path = REPLACE(context_path, 'localhost', '" + output + "') WHERE context_path LIKE '%localhost%';"
See that + output + in BOLD? that’s the issue. In my program output is a variable that I define earlier, and need to include it in the string. BEFORE ANYONE SAYS I SHOULD USE THE ‘%s’ method for inserting into formatted strings, I KNOW. I like this method so I can actually READ THE STRING. Fight me.
SO why does this occur? The reason is that Python, for whatever reason, has a nasty habit of adding “special characters” and in particular the \n or NewLine character when you do something like that with a string. Want to know if it is happening? Throw this line in your code (the repr() is the key part as it prints special characters):
print repr(sql_cmd)
What you will see in the output, is a ‘\n’ in there after the variable is inserted, and the rest of the string on a new line. No errors or warnings, but things will definitely not work. So, how to fix it? Throw this line in:
sql_cmd = sql_cmd.replace('\n', '')

I am going to stat making it a “best practice” to include that line (with the correct string variable name) anytime I work with strings. It will save me many lost hours of “why the actual f$%^ is this not working?!?!?” moments, and I hope it will help you too!