简体   繁体   English

当字符串包含“ \\”和Python中的特殊字符时,如何删除字符集

[英]How to remove set of characters when a string comprise of “\” and Special characters in python

a = "\\Virtual Disks\\DG2_ASM04\\ACTIVE"

From the above string I would like to get the part "DG2_ASM04" alone. 从上面的字符串中,我想单独获得"DG2_ASM04"部分。 I cannot split or strip as it has the special characters "\\" , "\\D" and "\\A" in it. 我无法拆分或剥离,因为其中包含特殊字符"\\""\\D""\\A"

Have tried the below and can't get the desired output. 尝试了以下内容,但无法获得所需的输出。

a.lstrip("\Virtual Disks\\").rstrip("\ACTIVE")

the output I have got is: 'G2_ASM04' instead of "DG2_ASM04" 我得到的输出是: 'G2_ASM04' instead of "DG2_ASM04"

Simply use slicing and escape backslash( \\ ) 只需使用slicingescape反斜杠( \\

>>> a.split("\\")[-2]
'DG2_ASM04'

In your case D is also removing because it is occurring more than one time in given string (thus striping D as well). 在您的情况下, D也要删除,因为它在给定的字符串中出现了多次(因此也剥离了D )。 If you tweak your string then you will realize what is happening 如果您调整弦乐,那么您将意识到发生了什么

>>> a = "\Virtual Disks\XG2_ASM04\ACTIVE"
>>> a.lstrip('\\Virtual Disks\\').rstrip("\\ACTIVE")
'XG2_ASM04'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM