python regex每当数字与非数字相邻时就添加空间 [英] python regex add space whenever a number is adjacent to a non-number

查看:74
本文介绍了python regex每当数字与非数字相邻时就添加空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将非数字与Python字符串中的数字分开.数字可以包含浮点数.

I am trying to separate non-numbers from numbers in a Python string. Numbers can include floats.

Original String               Desired String
'4x5x6'                       '4 x 5 x 6'
'7.2volt'                     '7.2 volt'
'60BTU'                       '60 BTU'
'20v'                         '20 v'
'4*5'                         '4 * 5'
'24in'                        '24 in'

关于如何在PHP中实现这一目标,这是一个很好的线索:

Here is a very good thread on how to achieve just that in PHP:

Regex:如果字母与相邻,则添加空格一个数字

我想在Python中操纵上面的字符串.

I would like to manipulate the strings above in Python.

以下代码在第一个示例中有效,但在其他示例中无效:

Following piece of code works in the first example, but not in the others:

new_element = []
result = [re.split(r'(\d+)', s) for s in (unit)]
for elements in result:
   for element in elements:
       if element != '':
           new_element.append(element)

    new_element = ' '.join(new_element)
    break

推荐答案

容易!只需将其替换并使用Regex变量即可.不要忘记去除空格. 请尝试以下代码:

Easy! Just replace it and use Regex variable. Don't forget to strip whitespaces. Please try this code:

import re
the_str = "4x5x6"
print re.sub(r"([0-9]+(\.[0-9]+)?)",r" \1 ", the_str).strip() // \1 refers to first variable in ()

这篇关于python regex每当数字与非数字相邻时就添加空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆