So I've got a problem I'm trying to solve using a python expression in a "Calculate Value" step in Model Builder. In short, I'm trying to replace new line characters (\n) with "" to change a multi-line input text string (from a text file) to a single line of text (which will play nice with Field Calculator). However, it seems that I can't find a way to make the characters "\n" stay in my expression. As soon as I click out of the Code Block, the characters disappear and the following line of script moves down onto a new line. I've tried the 2 below combinations with the same result (3rd image). In a standalone python script, this doesn't happen. Would you consider this a bug?
Solved! Go to Solution.
The work around was to pass in the new line character as part of the function call, so I have this model:
The Calculate Value tool is this:
chr(10) is equivalent to "\n".
print(f"X{chr(10)}X")
X
X
Or the os.linesep workaround noted in the bug @DuncanHornby submitted. 2019, that's pretty poor...
I just tried my code block with the line you suggested.
Assuming I've written it correctly, it still doesn't seem to work (I have tried chr(10), "chr(10)", {chr(10)} and "{chr(10}" as well without any luck). All come up with the below error.
I don't think the bug with "\n" in the code block is the problem. You're actually passing a multi line string literal into the Result function
Expression:
Result(r"%Value (3)%")
Is getting converted by ArcGIS to:
Result(r"Your text file
contents with
lots of
new
lines...")
Which is a syntax error.
You can use triple quotes to handle multi line string literals (did you see my other post?)
Result(r"""%Value (3)%""")
You're right - I forgot to include the triple quotes (yes, I had seen the other post). I added them in and it worked - sort of. I gave me a result, but one that still contains the new line characters. I believe the triple quotes has solved the input value issue, but still hasn't resulted in a query that removes the new line values from the output value.
However.....
I tried out Duncan's suggestion of putting the new line characters into the function call, and TaDa! Managed to get out a single line of text!
This is good news because now I can do away with the separate python script tool that I was using the achieve the same result! Thanks all for your input and patience!
The work around was to pass in the new line character as part of the function call, so I have this model:
The Calculate Value tool is this:
I logged this as bug in 2019, its disappointing that they still have not fixed it in 3 years! I remember the support response offered up a ridiculous work around and clearly were not understanding the impact that this bug would have, i.e. as you are discovering making it impossible to write code in a Calculate Value tool in model builder if you use standard python \n notation.