我以為這是一個簡單的問題,我搜索了很多,但沒有找到合適的!在python中用'/'替換'\'時如何擺脫字串中的“轉義序列”?我需要將 Windows 路徑轉換為 ??Unix 路徑,但例如 'blahblah\nblahblah' 或 'blahblah\bblahblah' 會出現問題!
addressURL = "B:\shot_001\cache\nt_02.abc"
addressURL = addressURL.replace('\\','/')
print(addressURL)
# Result: B:/shot_001/cache
t_02.abc #
我也使用了 os.path 模塊,但結果是一樣的!
無論如何,我需要將“B:\shot_001\cache\nt_02.abc”轉換為“B:/shot_001/cache/nt_02.abc”
謝謝
uj5u.com熱心網友回復:
如果您只想轉換:
"B:\shot_001\cache\nt_02.abc"
...至:
"B:/shot_001/cache/nt_02.abc"
...你可以試試這個:
string = r"B:\shot_001\cache\nt_02.abc"
new_string = '/'.join(string.split('\\'))
注意:r將字串放在字串前面很重要 - 這表示字串為“原始字串”,并有助于join將特殊\n字符視為任何其他文本,而不是作為回車符。在此處了解有關原始字串的更多資訊。
如果您正在尋找一種更好的方式來處理一般路徑,我建議您查找pathlib:pathlib docs
如果你得到一個不是以“Raw”開頭的字串:
這需要幾次嘗試...
s1 = 'B:\shot_001\cache\nt_02.abc'
s1 = repr(s1)[1:-1]
s2 = [each for each in (s1).split("\\") if each]
s2 = '/'.join(s2)
print (s2)
這會產生:
B:/shot_001/cache/nt_02.abc
這借鑒了這里的指導。
uj5u.com熱心網友回復:
這是我在網上找到的最好的解決方案(感謝匿名作者)。這個問題并不像我想象的那么容易:
import os
import re
def slashPath(path):
"""
param: str file path
return: str file path with "\\" replaced by '/'
"""
path = rawString(path)
raw_path = r"{}".format(path)
separator = os.path.normpath("/")
changeSlash = lambda x: '/'.join(x.split(separator))
if raw_path.startswith('\\'):
return '/' changeSlash(raw_path)
else:
return changeSlash(raw_path)
def rawString(strVar):
"""Returns a raw string representation of strVar.
Will replace '\\' with '/'
:param: str String to change to raw
"""
if type(strVar) is str:
strVarRaw = r'%s' % strVar
new_string=''
escape_dict={'\a':r'\a', '\b':r'\b', '\c':r'\c', '\f':r'\f', '\n':r'\n',
'\r':r'\r', '\t':r'\t', '\v':r'\v', '\'':r'\'', '\"':r'\"',
'\0':r'\0', '\1':r'\1', '\2':r'\2', '\3':r'\3', '\4':r'\4',
'\5':r'\5', '\6':r'\6', '\7':r'\7', '\8':r'\8', '\9':r'\9'}
for char in strVarRaw:
try: new_string =escape_dict[char]
except KeyError: new_string =char
return new_string
else:
return strVar
#--------- JUST FOR RUN -----------
s1 = 'cache\bt_02.abc'
print(slashPath(s1))
#result = cache/bt_02.abc
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/531326.html
上一篇:將“01”從字串決議為rust中的數字時出現強制錯誤
下一篇:將字串正確拆分為陣列陣列
