Python, like many other languages, uses single ('
) and double quotes ("
) for multi-character strings. This was a bit for me to digest coming from the C++ world where single and double quotes have distinct uses: single quotes for a character and double quotes for strings.
Functionally, there’s no difference between single and double quotes in Python, but they can be played off each other and alleviate the need to use the escape characters \'
and \"
.
Let’s suppose you’re creating middleware and want to write the OpenSees analysis
and analyze
commands to a file. We can use double quotes around the commands and single quotes around the Static
analysis type.
import openseespy.opensees as ops
output = open("convertedModel.py",'w') # C++ style, but whatevs
#
# Do some stuff
#
Nsteps = 100
output.write("ops.analysis('Static')\n")
output.write(f"ops.analyze({Nsteps})\n")
output.close()
Notice the use of an f-string to substitute the Nsteps
variable into the string.
We can also use single quotes around the commands. But in doing so, we have to switch to double quotes around Static
.
output.write('ops.analysis("Static")\n')
output.write(f'ops.analyze({Nsteps})\n')
If you insist on single quotes everywhere in convertedModel.py
, you have to escape the quotes around Static
, which can be visually distracting mid-string. Same idea if you want double quotes everywhere.
output.write('ops.analysis(\'Static\')\n')
# output.write("ops.analysis(\"Static\")\n")
There’s plenty more nuance to quotes and escape characters, but I’ll keep the blog focused on the nuances of OpenSees.