Calvin
Calvin

Reputation: 19

Python 3.6 - How Do I Format Variables and Literals In A .Write Statement?

... (Be advised the actual values in the data below are not static nor that important, but are only an example.)

Specifically, I am needing assistance on understanding what I did wrong with the format and syntax and what is the proper way. Anyway, here goes.

I need the following Python 3.6 code...

stella = open(stellocation + "\\scripts\\sh4.ssc",'w')
stella.write("core.setDate(\""+date+"T"+time+":00", "UTC""); ")\n)
stella.write("core.setObserverLocation("+longitude +", "+latitude+", 6, 0, "SH4 Navigation Point, ""+ ocean +", "earth")");
stella.close()

...to produce this text...

core.setDate("1943-01-01T10:01:00","UTC");
core.setObserverLocation(-161.605158333, 19.2008553333, 6, 0, "USS Perch (Pacific Ocean)", "Earth");

...I keep getting this error...

  File "C:\DAATAPOND\Python Scripts\SH4toStellarium.py", line 54
    stella.write("core.setDate(\""+date+"T"+time+":00"") ")\n)
                                                              ^
SyntaxError: unexpected character after line continuation character

I have been researching and experimenting for three days without success. I have read and attempted to digest a number of websites on the ".write" function statement. They tended to be arcane and left me somewhat confused. I decided it was time to seek help. :)

Please let me know if I can be of any assistance.

Take care, Calvin

PS - This is my first question on StackOverflow. Please let me know if anything should be different.

Upvotes: 0

Views: 107

Answers (2)

Barmar
Barmar

Reputation: 782564

Use an f-string to make variable substitution easier. And if you want to put literal double-quotes in the string, wrap it in single quotes so you don't need to escape them.

The syntax error is because you put \n outside the string and added an extra ).

stella.write(f'core.setDate("{date}T{time}:00","UTC");\n')
stella.write(f'core.setObserverLocation({longitude}, {latitude}, 6, 0, "SH4 Navigation Point, ({ocean})", "Earth");')

Upvotes: 1

Abhyuday Vaish
Abhyuday Vaish

Reputation: 2379

It should be something like this: stella.write("core.setDate(\""+date+"T"+time+":00"") \n")

Where you went wrong: You were using an extra bracket at the end of the above line and \n was outside the quoted string.

Upvotes: 1

Related Questions