作者LessonWang (橘白Cat)
看板Python
标题Re: [问题] GUID 字串格式转换
时间Fri Jul 21 09:32:45 2017
※ 引述《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://webptt.com/cn.aspx?n=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
1F:→ LessonWang: 後来看完了之後才发现 07/21 09:55
2F:→ LessonWang: 补零的部分 做一下修正 07/21 09:55
3F:→ LessonWang: for i in range(len(tmp)): 07/21 09:55
4F:→ LessonWang: if i == 0: 07/21 09:55
5F:→ LessonWang: tmp[i] = tmp[i][2:].zfill(8) 07/21 09:55
6F:→ LessonWang: elif i == 1 or i == 2: 07/21 09:55
7F:→ LessonWang: tmp[i] = tmp[i][2:].zfill(4) 07/21 09:55
8F:→ LessonWang: else: 07/21 09:55
9F:→ LessonWang: tmp[i] = tmp[i][2:].zfill(2) 07/21 09:55
10F:→ LessonWang: 然後formatted_guid可以简化成 07/21 13:45
11F:→ LessonWang: formatted_guid = "-".join([*tmp[0:2],"".join(tmp[3 07/21 13:45
12F:→ LessonWang: :5]),"".join(tmp[ 07/21 13:45
13F:→ LessonWang: 5:])]) 07/21 13:45