【问题标题】:add space between number and string python [closed]在数字和字符串python之间添加空格[关闭]
【发布时间】:2020-04-13 08:42:08
【问题描述】:

我想在数字和文字之间添加空格

示例字符串:ABC24.00XYZ58.28PQR

输出:ABC 24.00 XYZ 58.28 PQR

请告诉我答案。

非常感谢。

【问题讨论】:

    标签: python regex string python-re


    【解决方案1】:

    您可以使用re.sub 反向引用捕获的组来添加空格:

    s = 'ABC24.00XYZ58.28PQR'
    
     re.sub('(\d+(\.\d+)?)', r' \1 ', s).strip()
    # 'ABC 24.00 XYZ 58.28 PQR'
    

    demo

    【讨论】:

      【解决方案2】:

      如果没有更多要求,你可以使用正则表达式:

      import re
      
      s = "ABC24.00XYZ58.28PQR"
      s = re.sub("[A-Za-z]+",lambda group:" "+group[0]+" ",s)
      print(s.strip())
      

      【讨论】:

      • 您可以反向引用捕获的组,如\1,参见here
      【解决方案3】:

      您可以使用re.split 将输入字符串分隔为令牌列表。然后用空格连接所有这些标记。

      import re
      
      s = "ABC24.00XYZ58.28PQR"
      split = [c for c in re.split(r'([-+]?\d*\.\d+|\d+)', s) if c]
      result = " ".join(split)
      print(result)
      

      输出:

      ABC 24.00 XYZ 58.28 PQR
      

      正则表达式r'([-+]?\d*\.\d+|\d+)' 应该相当健壮,并且还可以检测-12+5.0 类型的浮点数。

      【讨论】:

        【解决方案4】:

        连接字符串并将数字转换为字符串类型:

        print ("AB" + " "+ str(34)) //or
        print ("AB " + str(34))
        

        如果您想在字符串中添加空格,请使用 Regex 参考: python regex add space whenever a number is adjacent to a non-number

        【讨论】:

        • 似乎问题是在询问转换,而不仅仅是创建字符串。
        猜你喜欢
        • 1970-01-01
        • 2023-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-27
        • 2012-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多