Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a string in python with double and single quotes

Tags:

python

I am using python to communicate with the OS.

I need to create a string of the following form:

string = "done('1') && done('2')"

Note that my string MUST have the double quotes in it, but I am not sure how to do that since the double quotes are used in python for defining a string.

Then I do something like:

os.system(string)

But the system would only read the string with the double and single quotes in it.

I tried:

>>> s = '"done('1') && done('2')"'
  File "<stdin>", line 1
    s = '"done('1') && done('2')"'
                ^
SyntaxError: invalid syntax

I also tried the triple quotes suggested here but i get an error:

>>> s = """"done('1') && done('2')""""
  File "<stdin>", line 1
    s = """"done('1') && done('2')""""
                                     ^
SyntaxError: EOL while scanning string literal
like image 305
Dnaiel Avatar asked Oct 28 '25 15:10

Dnaiel


2 Answers

When you use a triply quoted string you need to remember that the string ends when Python finds a closing set of three quotes - and it is not greedy about it. So you can:

Change to wrapping in triple single quotes:

my_command = '''"done('1') && done('2')"'''

Escape the ending quote:

my_command = """"done('1') && done('2')\""""

or add space around your quotes and call strip on the resulting string:

my_command = """
"done('1') && done('2')"
""".strip()
# Blank lines are for illustrative purposes only
# You can do it all on one line as well (but then it looks like you have
# 4 quotes (which can be confusing)
like image 51
Sean Vieira Avatar answered Oct 30 '25 09:10

Sean Vieira


You can escape both kinds of quotes:

s = '"done(\'1\') && done(\'2\')"'
like image 39
wRAR Avatar answered Oct 30 '25 09:10

wRAR