Raw string fails to compile with "no viable alternative at input '\n'

I'm using Ignition 8.1.

From reading the Strings - Ignition University, it seemed to me that the following two string assignments would be equivalent:

path = "C:\\Temp\\pHData\\Ignition\\"

path = r"C:\Temp\pHData\Ignition\"

However, the second one fails to compile, giving the error "no viable alternative at input '\n' "

To me, the second one looks the same as this example from the document:

# Specifying a Windows file path
myPath = r"C:\Folder\Another Folder\file.txt"
print myPath

Just wondering what I'm missing?

In python the \ character is an escape character, so you are escaping the " at the end of the string. This is kind of an edge case. However, removing that \ is functionally equivalent. If you intend to use this as a sub string in building a larger path, then adding format place holders will allow you to use this as you're trying.

basePath = r"C:\Temp\pHData\Ignition\{}"
extendedPath = "SomeChildFolder"
print basePath.format(extendedPath)

Another alternative would be to use a string builder

1 Like

In basically everything in Python and Java's standard library, you can just use forward slashes instead of backslashes and avoid any escaping problems entirely.

3 Likes

Thanks for the reply, Irose!

So, even on a 'raw' string, the backslash at the end acts as an escape? I'm having trouble making sense of that since it didn't do that with the other backslashes in the string. Any idea why only the last character seems to be a special case?

Good to know about the forward slashes, thanks!

In the first example there are two \\ so you're escaping the \ and not the ". The \ escapes the next character.

It needs to work this way, what if you want to include quotes in a string with out terminating the string?

myString = "This is a \"string\" that has quotes."

A raw string can not end in a single backslash.

1 Like

Again, thanks for the response.

For those (like me) who are still having trouble understanding it, I just stumbled across this document that explains about this particular topic for Python in general.
Why can't raw strings in Python end with a backslash?

It still seems odd to me. But I tend to remember odd things, so maybe that's good? :slightly_smiling_face:

1 Like

What if production has a database with thousands of records that are just file paths on a network drive?

One path example would be "C:\folder1\folder2\folder3\items", that is how they're stored in our DB. I am trying to pull the paths from the db and then represent them in a tree view.

If you're not manually inputting the string then it shouldn't matter. However, if you're concerned then you can just do:

path = r'C:\folder1\folder2\folder3\items'
path = path.replace('\\','/')

EDIT: I hand typed in the path for testing purposes.

2 Likes