Skip to content Skip to sidebar Skip to footer

Python String Invalid Syntax

This is my code: onedata = str('& 'C:\Program Files\Windows Media Player\wmplayer.exe'') print (onedata) Im trying to run it but it says: onedata = str('& 'C:\Program

Solution 1:

You closed the string before you should have. I'm guessing you want the literal " in the string, so you need this:

onedata = str("& \"C:\\Program Files\\test.test")

\" makes a literal " character. and \\ makes a literal \ character. This is so that the compiler doesn't get confused between the literal meaning of a character and its syntactic meaning.

Solution 2:

You can escape the second double quotes with \. Or you can use single outer quotes:

onedata = str('& "C:\Program Files\Windows Media Player\wmplayer.exe"')

print(onedata)

& "C:\Program Files\Windows Media Player\wmplayer.exe"

Solution 3:

put a back lash behind the second ( " ) to solve it

Solution 4:

The answers above are excellent, but they don't mention another solution that I personally find easier than using escape characters. In Python, you can use single quotes ('') or double quotes ("") for a string, and if you want to use a double quote inside the string, you can use single quotes to denote your string. Example:

'This is " a string'

is the same as:

"This is \" a string"

Post a Comment for "Python String Invalid Syntax"