簡體   English   中英

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

[英]How to extract a substring from a string in Python?

假設我有一個字符串,text2 ='C:\\ Users \\ Sony \\ Desktop \\ f.html',我想分開“C:\\ Users \\ Sony \\ Desktop”和“f.html”並將它們存儲在不同的變量中那我該怎么辦? 我嘗試了正則表達式,但我沒有成功。

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM