【问题标题】:How to insert hyphens into a UUID string? [duplicate]如何在 UUID 字符串中插入连字符? [复制]
【发布时间】:2021-03-31 18:26:50
【问题描述】:

我想创建一个函数,在 UUID 字符串的第 8、12、16、20 位添加 -

例子:

Original: 76684739331d422cb93e5057c112b637
New: 76684739-331d-422c-b93e-5057c112b637

我不知道如何将它定位在一个看起来不像意大利面条代码的字符串中的多个位置。

【问题讨论】:

标签: python uuid


【解决方案1】:

正则表达式是另一种方式,\S 匹配任何非空白字符,{} 中的数字是字符数。

import re
​
new=re.sub(r'(\S{8})(\S{4})(\S{4})(\S{4})(.*)',r'\1-\2-\3-\4-\5',original)

print(new)

# 76684739-331d-422c-b93e-5057c112b637

【讨论】:

    【解决方案2】:

    鉴于以下论点:

    delimiter = '-'
    indexes = [8,12,16,20]
    string = '76684739331d422cb93e5057c112b637'
    

    您可以将list comprehensionjoin 一起使用:

    idx = [0] + indexes + [len(string)]
    delimiter.join([string[idx[i]:idx[i+1]] for i in range(len(idx)-1)])
    

    输出:

    '76684739-331d-422c-b93e-5057c112b637'
    

    【讨论】:

      【解决方案3】:

      您似乎正在使用 UUID。 library 是 Python 的标准配置:

      import uuid
      s = '76684739331d422cb93e5057c112b637'
      u = uuid.UUID(hex=s)
      print(u)
      
      76684739-331d-422c-b93e-5057c112b637
      

      【讨论】:

        【解决方案4】:

        您可以通过切片逐步追加新字符串来做到这一点:

        original = "76684739331d422cb93e5057c112b637"
        indices = [8, 12, 16, 20]
        delimiter = "-"
        
        new_string = ""
        prev = 0
        for index in indices:
            new_string += original[prev:index] + delimiter
            prev = index
        new_string += original[prev:]
        
        print(new_string)
        # 76684739-331d-422c-b93e-5057c112b637
        

        【讨论】:

          猜你喜欢
          • 2019-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-18
          • 2013-05-29
          相关资源
          最近更新 更多