[英]Finding string between 2 specific character
I have a list of directories: 我有一个目录列表:
C:\level1\level2\level3\level4\level5\level6\level7
I need a way to extract "level4"
and "level5"
. 我需要一种提取"level4"
和"level5"
。
Aka. 阿卡。 I need to extract the string between the 4th and 5th backlash and the string between the 5th and 6th backslash. 我需要提取第4个和第5个反斜杠之间的字符串以及第5个和第6个反斜杠之间的字符串。
How would I go about doing this? 我将如何去做呢?
Try splitting by backslash : 尝试按反斜杠分割:
s = "C:\level1\level2\level3\level4\level5\level6\level7"
l = s.split('\\')
print l[4], l[5]
>>> s = r'C:\level1\level2\level3\level4\level5\level6\level7'
>>> words = s.split('\\') # Escape backslash or use rawstring - r'\'
>>> words[4]
'level4'
>>> words[5]
'level5'
If you want to join those two words, then use str.join
如果要连接这两个词,请使用str.join
>>> ' '.join((words[4],words[5]))
'level4 level5'
Also if you want a list of levels, 另外,如果您想要一个级别列表,
>>> ' '.join(words[i] for i in [4,5,6])
'level4 level5 level6'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.