简体   繁体   中英

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" .

Aka. I need to extract the string between the 4th and 5th backlash and the string between the 5th and 6th backslash.

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]

Use str.split

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

>>> ' '.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'

You can use str.split to split a string according to a specific delimiter.

path = r'C:\level1\level2\level3\level4\level5\level6\level7'
dirs  = path.split('\\')

print dirs[4], dirs[5]
# will print:
# level4 level5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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