Re: [問題] GUID 字串格式轉換
※ 引述《LwHow (Do)》之銘言:
: 各位先進
: 小弟剛初學不久
: 想跟大家請教一下
: 如果想將下面這個String
: 0x798ffd60, 0xf10e, 0x4ac4, 0x89, 0x39, 0xc8, 0xbe, 0xab, 0xfe, 0x55, 0xb4
: 轉換成格式成下面格式
: 798ffd60-f10e-4ac4-8939-c8beabfe55b4
: 有什麼比較漂亮的寫法嗎?
: 有一個重點就是,格式必須要符合寬度
: 例如 第一組資料如果是0xffd60,則我們必須把資料補滿為
: 000ffd60-xxxx-xxxx-xxxx-xxxxxxxx
: 其他欄位以此類推
: 下面是我的Sample code(有點硬來...讓大家傷眼了Orz)
: def FillZeroByWidth(Str, Width):
: Str = Str[2:].zfill(Width)
: return Str
: def FillZeroGuid(Str):
: tmpList = Str.split(", ")
: tmpStr = ""
: tmpStr += fillzerobywidth(tmpList[0], 8)
: tmpStr += fillzerobywidth(tmpList[1], 4)
: tmpStr += fillzerobywidth(tmpList[2], 4)
: tmpStr += fillzerobywidth(tmpList[3], 2)
: tmpStr += fillzerobywidth(tmpList[4], 2)
: tmpStr += fillzerobywidth(tmpList[5], 2)
: tmpStr += fillzerobywidth(tmpList[6], 2)
: tmpStr += fillzerobywidth(tmpList[7], 2)
: tmpStr += fillzerobywidth(tmpList[8], 2)
: tmpStr += fillzerobywidth(tmpList[9], 2)
: tmpStr += fillzerobywidth(tmpList[10], 2)
: return tmpStr
: def strInsertIndex(Str, Index, Char):
: return Str[:Index] + Char + Str[Index:]
: def modifyGuidFormat(Str):
: tmpStr = FillZeroGuid(Str)
: tmpStr = strInsertIndex(tmpStr, 8, "-")
: tmpStr = strInsertIndex(tmpStr, 13, "-")
: tmpStr = strInsertIndex(tmpStr, 18, "-")
: tmpStr = strInsertIndex(tmpStr, 23, "-")
: return tmpStr
: def main():
: tmpGuid = modifyGuidFormat(Guid)
: 謝謝!
手邊沒電腦
只好憑空寫一下 看能不能達到你的需求
tmp = guid.split(", ")
for i in range(len(tmp)):
tmp[i] = tmp[i][2:].zfill(len(tmp[i])-2)
formatted_guid = "-".join([tmp[0],tmp[1],tmp[2],"".join(tmp[3:5]),"".join(tmp[5:])])
-----
Sent from JPTT on my Asus ASUS_Z00UD.
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 27.246.75.220
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1500600766.A.9D7.html
※ 編輯: LessonWang (27.246.75.220), 07/21/2017 09:34:02
※ 編輯: LessonWang (27.246.75.220), 07/21/2017 09:37:06
→
07/21 09:55, , 1F
07/21 09:55, 1F
→
07/21 09:55, , 2F
07/21 09:55, 2F
→
07/21 09:55, , 3F
07/21 09:55, 3F
→
07/21 09:55, , 4F
07/21 09:55, 4F
→
07/21 09:55, , 5F
07/21 09:55, 5F
→
07/21 09:55, , 6F
07/21 09:55, 6F
→
07/21 09:55, , 7F
07/21 09:55, 7F
→
07/21 09:55, , 8F
07/21 09:55, 8F
→
07/21 09:55, , 9F
07/21 09:55, 9F
→
07/21 13:45, , 10F
07/21 13:45, 10F
→
07/21 13:45, , 11F
07/21 13:45, 11F
→
07/21 13:45, , 12F
07/21 13:45, 12F
→
07/21 13:45, , 13F
07/21 13:45, 13F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 4 篇):
問題
2
5