Home > Software engineering >  how do I create a string using a backslash and a variable in python?
how do I create a string using a backslash and a variable in python?

Time:02-28

I'm trying to execute this command on a Windows machine:

dir \\hostname\sapmnt\SID\SYS\profile\SID_*04_hostname /b /a-d

So far, I have this code:

cmd_drive = r"\\"
local_hostname = "hostname"
current_sid = "SID"
currentline_instance_number = "04"
cmd_pf = os.path.join(cmd_drive, local_hostname, "sapmnt", current_sid, "SYS", "profile")
cmd_pf = cmd_pf   str(current_sid)   "_*"   str(currentline_instance_number)   "_"   str(currentline_host)
cmd_pf = "dir "   cmd_pf   " /b /a-d"
print(cmd_pf)

which produces this output:

dir \\hostname\sapmnt\SID\SYS\profileSID_*04_hostname /b /a-d

So, I need a backslash before the final part of the string ("SID_*04_hostname /b /a-d")

CodePudding user response:

Add a "\\" to create a backslash in the desired place:

cmd_drive = r"\\"
    local_hostname = "hostname"
    current_sid = "SID"
    currentline_instance_number = "04"
    cmd_pf = os.path.join(cmd_drive, local_hostname, "sapmnt", current_sid, "SYS", "profile")
    cmd_pf = cmd_pf   "\\"   str(current_sid)   "_*"   str(currentline_instance_number)   "_"   str(currentline_host)
    cmd_pf = "dir "   cmd_pf   " /b /a-d"
    print(cmd_pf)`
  • Related