如何使用反斜杠和 python 中的变量创建字符串?

how do I create a string using a backslash and a variable in python?

我正在尝试在 Windows 机器上执行此命令:

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

到目前为止,我有这个代码:

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)

产生此输出:

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

所以,我需要在字符串的最后部分之前加一个反斜杠 ("SID_*04_hostname /b /a-d")

在所需位置添加“\\”以创建反斜杠:

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)`