Python 字符串转换,去掉空格,加连字符

Python string conversion, take out spaces, add hyphens

我在 pandas 数据框中有一列,其格式类似于

f1 d3 a4 0a d0 6a 4b 4a 83 d4 4f c9 1f 15 11 17

我想将其转换为:

f1d3a40a-d06a-4b4a-83d4-4fc91f151117

我知道我可以使用 replace(" ", "") 去掉空格,但我不确定如何在我需要的确切位置插入连字符。

我也不确定如何将它应用于 pandas 系列对象。

如有任何帮助,我们将不胜感激!

这看起来像一个 UUID,所以我只使用那个模块

>>> import uuid
>>> s = 'f1 d3 a4 0a d0 6a 4b 4a 83 d4 4f c9 1f 15 11 17'
>>> uuid.UUID(''.join(s.split()))
UUID('f1d3a40a-d06a-4b4a-83d4-4fc91f151117')
>>> str(uuid.UUID(''.join(s.split())))
'f1d3a40a-d06a-4b4a-83d4-4fc91f151117'

编辑:

df = pd.DataFrame({'col':['f1 d3 a4 0a d0 6a 4b 4a 83 d4 4f c9 1f 15 11 17',
                          'f1 d3 a4 0a d0 6a 4b 4a 83 d4 4f c9 1f 15 11 17']})

df['col'] = df['col'].str.split().str.join('').apply(uuid.UUID)
print (df)
                                    col
0  f1d3a40a-d06a-4b4a-83d4-4fc91f151117
1  f1d3a40a-d06a-4b4a-83d4-4fc91f151117
a = "f1 d3 a4 0a d0 6a 4b 4a 83 d4 4f c9 1f 15 11 17"
c = "f1d3a40a-d06a-4b4a-83d4-4fc91f151117"
b = [4,2,2,2,6]

def space_2_hyphens(s, num_list,hyphens = "-"):
    sarr = s.split(" ")
    if len(sarr) != sum(num_list):
        raise Exception("str split num must equals sum(num_list)")
    out = []
    k = 0
    for n in num_list:
        out.append("".join(sarr[k:k + n]))
        k += n
    return hyphens.join(out)


print(a)
print(space_2_hyphens(a,b))
print(c)