如何从Python中的字符串中提取子字符串?

时间:2015-10-29 16:05:37

标签: python python-2.7

假设我有一个字符串,text2 =' C:\ Users \ Sony \ Desktop \ f.html',我想分开" C:\ Users \ Sony \ Desktop&#34 ;和" f.html"并将它们存储在不同的变量中,那么我该怎么办?我尝试了正则表达式,但我没有成功。

1 个答案:

答案 0 :(得分:3)

os.path.split做你想做的事:

>>> import os
>>> help(os.path.split)
Help on function split in module ntpath:

split(p)
    Split a pathname.

    Return tuple (head, tail) where tail is everything after the final slash.
    Either part may be empty.

>>> os.path.split(r'c:\users\sony\desktop\f.html')
('c:\\users\\sony\\desktop', 'f.html')
>>> path,filename = os.path.split(r'c:\users\sony\desktop\f.html')
>>> path
'c:\\users\\sony\\desktop'
>>> filename
'f.html'