python分隔符的使用,在python中使用分隔符“\”拆分字符串
這里有兩個(gè)問(wèn)題。在
路徑分割
通常使用os.path.split來(lái)處理路徑:>>> import os.path
>>> p=r'C:\Users\xyz\filename.txt'
>>> head, tail = os.path.split(p)
>>> head
'C:\\Users\\xyz'
>>> tail
'filename.txt'
注意:os.path使用它所使用的操作系統(tǒng)的路徑格式。如果您知道您特別想使用Windows路徑(即使您的程序是在Linux或OSX上運(yùn)行的),那么您應(yīng)該使用os.path模塊而不是ntpath模塊。See the note:Note Since different operating systems have different path name conventions, there are several versions of this module in the standard library. The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths. However, you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats. They all have the same interface:posixpath for UNIX-style paths
ntpath for Windows paths
macpath for old-style MacOS paths
os2emxpath for OS/2 EMX paths
格式支持
有兩種格式可支持:在文件://C:\Users\xyz\文件名.txt在
C: \用戶\xyz\文件名.txt在
2是正常的Windows路徑,1是。。。坦白說(shuō),我不知道那是什么。它看起來(lái)有點(diǎn)像file URI,但使用了Windows樣式的分隔符(反斜杠)。這很奇怪。當(dāng)我在Windows上用Chrome打開PDF時(shí),URI看起來(lái)不一樣:
^{pr2}$
我假設(shè)這就是你感興趣的格式。如果沒(méi)有,那么我不能保證你在處理什么,你可以對(duì)如何解釋它做一些有根據(jù)的猜測(cè)(去掉file://前綴,將其視為Windows路徑?)。在
可以使用the ^{} module將一個(gè)URI拆分成有意義的部分(參見(jiàn)python3的urllib.parse),一旦提取了URI的路徑部分,就可以.split('/')它(URI語(yǔ)法非常簡(jiǎn)單,可以實(shí)現(xiàn)這一點(diǎn))。如果在file://URI上使用此模塊,會(huì)發(fā)生以下情況:>>> r = urlparse.urlparse(r'file:///C:/Users/xyz/filename.txt')
>>> r
ParseResult(scheme='file', netloc='', path='/C:/Users/xyz/filename.txt', params='', query='', fragment='')
>>> r.path
'/C:/Users/xyz/filename.txt'
>>> r.path.lstrip('/').split('/')
['C:', 'Users', 'xyz', 'filename.txt']
請(qǐng)閱讀this URI scheme description以更好地了解此格式的外觀,以及為什么file:后面有三個(gè)斜杠。在
總結(jié)
以上是生活随笔為你收集整理的python分隔符的使用,在python中使用分隔符“\”拆分字符串的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: “寂绝无人问病身”上一句是什么
- 下一篇: 夜来风雨声的作者是谁啊?