看板 Python 關於我們 聯絡資訊
我想問有關反轉str的問題 str="play" print str[::-1] #yalp print str[0:len(str):-1] #none print str[len(str):0:-1] #yal print str[len(str)::-1] #yalp print str[-1:-5:-1] #yalp 如果step為正[::1],start默認為0而end默認為len(str) 我不知道為負[::-1]的第一個空白start和第二個空白end會帶入什麼 一開始以為會等於這個str[0:len(str):-1],但不是 我想請問step為負的時候,前面兩個默認是什麼 我爬了一下 相關的文章是 https://www.ptt.cc/bbs/Python/M.1291617432.A.045.html -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.45.83.68 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1437578947.A.0D3.html
LiloHuang: 預設值都是 None,可試試 str[None:None:-1] 07/22 23:50
nicehorse06: str[None:None:-1] 可以耶 那填None要怎麼想? 07/22 23:54
LiloHuang: 這簡單,看 Python 原始碼便知,http://goo.gl/mL1928 07/22 23:58
LiloHuang: 在 PySlice_GetIndicesEx(...) 裡面有一段邏輯 07/22 23:58
LiloHuang: 基本上就是如果 step = -1,則 defstart = length - 1 07/22 23:59
LiloHuang: defstop = -1,因此會產生新的 list 裝載相反的順序 07/22 23:59
LiloHuang: 當然這個情況是在 start 跟 stop 都是 Py_None 的時候 07/23 00:02
LiloHuang: 才會使用 defstart 跟 defstop,看看原始碼你就懂了 :) 07/23 00:02
nicehorse06: 謝謝你,原來問題在原始碼 07/23 08:45
nicehorse06: 所以Python就是ㄧ個用C語言來寫的程式囉? 07/23 08:46
nicehorse06: 因此網路上說完美結合了C 07/23 08:47
LiloHuang: Python 有很多實作的版本,我猜測你是使用 CPython 07/23 09:03
LiloHuang: 像是 IronPython 跟 PyPy 就是不同的 interpreter 實作 07/23 09:04
LiloHuang: 其實這個問題官方文件有詳載 https://goo.gl/Tr13oP 07/23 09:04
LiloHuang: 坦白說文件我花了好一回才找到 XD 看實作原始碼比較快 07/23 09:09
nicehorse06: 我學的還很淺分不清楚版本,真的謝謝你用心的回答! 07/23 09:27
simpleplanya: 感謝!!!!! 08/31 22:09