python分隔符的使用,在python中使用分隔符“\”拆分字符串
這里有兩個問題。在
路徑分割
通常使用os.path.split來處理路徑:>>> 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使用它所使用的操作系統的路徑格式。如果您知道您特別想使用Windows路徑(即使您的程序是在Linux或OSX上運行的),那么您應該使用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是。。。坦白說,我不知道那是什么。它看起來有點像file URI,但使用了Windows樣式的分隔符(反斜杠)。這很奇怪。當我在Windows上用Chrome打開PDF時,URI看起來不一樣:
^{pr2}$
我假設這就是你感興趣的格式。如果沒有,那么我不能保證你在處理什么,你可以對如何解釋它做一些有根據的猜測(去掉file://前綴,將其視為Windows路徑?)。在
可以使用the ^{} module將一個URI拆分成有意義的部分(參見python3的urllib.parse),一旦提取了URI的路徑部分,就可以.split('/')它(URI語法非常簡單,可以實現這一點)。如果在file://URI上使用此模塊,會發生以下情況:>>> 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']
請閱讀this URI scheme description以更好地了解此格式的外觀,以及為什么file:后面有三個斜杠。在
總結
以上是生活随笔為你收集整理的python分隔符的使用,在python中使用分隔符“\”拆分字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: “寂绝无人问病身”上一句是什么
- 下一篇: php的运算符实践输入年份,[php第四