-1

So i'm still working on my personal assistent code but for some reason i can't have a "\" where i want it. I want my program to take the 2th word i speak and use it to run a program with that name.

if words[0] == "atlas":
  print("Succes")
  if words[1] == "launch":
    print("Launch Program")
    p = words[2] + ".exe"
    os.startfile("C:\Gebruikers\Jari\Snelkoppelingen\" + p)
  elif words[1] == "internet" and words[2] == "search":
    url = "https://www.google.be/webhp?hl=nl#hl=nl&q=" + '+'.join(words[3:])
    webbrowser.open_new_tab(url)
  else:
    print("Unknown Command")
else:
  print("Unknown Command")

The problem come's here:

os.startfile("C:\Gebruikers\Jari\Snelkoppelingen\" + p)

I need a "\" at the end of this line but it won't let me. Any suggestions?

DjKillerMemeStar
  • 425
  • 5
  • 18
  • 2
    `\ ` alone is an escape character, you need to write `\\ ` to get the literal backslash. – liborm May 29 '16 at 21:34
  • 5
    [How to print backslash with Python?](https://stackoverflow.com/questions/19095796/how-to-print-backslash-with-python) or [How to write string literals in python without having to escape them?](https://stackoverflow.com/questions/4703516/how-to-write-string-literals-in-python-without-having-to-escape-them) – Jonathan Lonowski May 29 '16 at 21:35
  • 2
    [Here](https://docs.python.org/2/reference/lexical_analysis.html#string-literals) is the python documentation on escape sequences. – A. Vidor May 29 '16 at 21:38
  • It is better to use forward slashes for a [Windows path in Python](https://stackoverflow.com/questions/2953834/) anyway. – Karl Knechtel Aug 07 '22 at 04:29

2 Answers2

0

\ is an escape character, which means "interpret the next character of this string in a special way"; for example, treat \n as a newline character. If you use it to escape \ itself, that says "treat this as a normal \ character.

Short answer: use \\ to represent a single \ character in a string.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

You need to "escape" a \ character with another \. Try:

"C:\\Gebruikers\\Jari\\Snelkoppelingen\\"
A. Vidor
  • 2,502
  • 1
  • 16
  • 24