如果它与前一个元素相同,我试图从build_location中拆分最后一个元素,但是预期的输出不一样,你能帮忙解决它吗?
build_location = "\\data\builds797\PROD\client.1.8-01180-STD.PROD-1\client.1.8-01180-STD.PROD-1"
buildid =build_location.split("\\")
if buildid[-1] == buildid[-2]:
#split the last element after "\"
build_location = build_location.split("\\")[-1]
print build_location
OUTPUT:-
client.1.8-01180-STD.PROD-1
EXPECTED OUTPUT:-
\\data\builds797\PROD\client.1.8-01180-STD.PROD-1
答案 0 :(得分:2)
变化:
build_location = build_location.split("\\")[-1]
要:
build_location = build_location.split("\\")[:-1]
# ---^---
你想要除最后一个之外的所有元素而不是最后一个元素。
这称为切片,您可以了解它。
之后,您应该将列表合并回一个字符串,并将额外的\
添加到:
'\\'+'\\'.join(build_location)
答案 1 :(得分:0)
那是因为你只是索引最后一个元素。您应该使用切片排除最后一项而不是最后一项上的索引:
if buildid[-1] == buildid[-2]:
#split the last element after "\"
build_location = build_location.split("\\")[:-1]
# ^^^^^
或者更好的是,对已经拆分的buildid
执行切片以避免重新分割:
if buildid[-1] == buildid[-2]:
#split the last element after "\"
build_location = buildid[:-1]
然后,要从切片重建原始字符串,请使用join
:
build_location = "\\".join(build_location)