【发布时间】:2016-08-09 10:49:07
【问题描述】:
我正在尝试将非数字与 Python 字符串中的数字分开。数字可以包括浮点数。
示例
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 中实现这一点的非常好的帖子:
Regex: Add space if letter is adjacent to a number
我想在 Python 中操作上面的字符串。
以下代码在第一个示例中有效,但在其他示例中无效:
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
【问题讨论】:
-
请发布您的尝试
-
那么您是否尝试过该线程中的任何内容?我确信
r'(?<=[a-zA-Z])(?=\d)|(?<=\d)(?=[a-zA-Z])'非常接近。 -
嗨,不幸的是 re.sub('/(?
-
您不能将正则表达式对象传递给
re方法,只能传递模式本身(请参阅上面的建议 - 这对您不起作用,但关闭)。 -
你好。非常感谢, re.sub(r'(?
标签: python regex replace formatting alphanumeric