问题
I am trying to separate non-numbers from numbers in a Python string. Numbers can include floats.
Examples
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'
Here is a very good thread on how to achieve just that in PHP:
Regex: Add space if letter is adjacent to a number
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
回答1:
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 ()
回答2:
I used split, like you did, but modified it like this:
>>> tcs = ['123', 'abc', '4x5x6', '7.2volt', '60BTU', '20v', '4*5', '24in', 'google.com-1.2', '1.2.3']
>>> pattern = r'(-?[0-9]+\.?[0-9]*)'
>>> for test in tcs: print(repr(test), repr(' '.join(segment for segment in re.split(pattern, test) if segment)))
'123' '123'
'abc' 'abc'
'4x5x6' '4 x 5 x 6'
'7.2volt' '7.2 volt'
'60BTU' '60 BTU'
'20v' '20 v'
'4*5' '4 * 5'
'24in' '24 in'
'google.com-1.2' 'google.com -1.2'
'1.2.3' '1.2 . 3'
Seems to have the desired behavior.
Note that you have to remove empty strings from the beginning/end of the array before joining the string. See this question for an explanation.
来源:https://stackoverflow.com/questions/36681439/python-regex-add-space-whenever-a-number-is-adjacent-to-a-non-number