-1

I have a string like: 'Treasury Notes 52.9 Certificates Of Deposit 15.9 Commercial Paper 15.9 Cash 15.3'

I want to split them in two parts: the numeric part and the non numeric one. For example: 'Treasury Notes', '52.9'.

I'm wondering how can I do that in Python.

Marios
  • 26,333
  • 8
  • 32
  • 52
  • Check this question which should help: https://stackoverflow.com/questions/12851791/removing-numbers-from-string – nordmanden Aug 22 '20 at 18:19

2 Answers2

0

You can try regex matches, to find letters & spaces and decimal numbers.

For example:

import re

s = 'Treasury Notes 52.9 Certificates Of Deposit 15.9 Commercial Paper 15.9 Cash 15.3'
matches = re.findall(r'[A-Za-z ]+|\d+\.\d+', s)
results = [x.strip() for x in matches] # theres probably a way to remove start & end space wih regex.
print(results)

Output:

['Treasury Notes', '52.9', 'Certificates Of Deposit', '15.9', 'Commercial Paper', '15.9', 'Cash', '15.3']
Greg
  • 4,468
  • 3
  • 16
  • 26
0

you can do this if you want a string result:

import re

st = 'Treasury Notes 52.9 Certificates Of Deposit 15.9 Commercial Paper 15.9 Cash 15.3'
pattern = re.compile(r"\d+\.\d+")

new_st = ""
for item in st.split():
    match = re.search(pattern, x)
    if match:
        new_st += f", {match.group()}, "
    else:
        new_st += f" {x}"

output:

 Treasury Notes, 52.9,  Certificates Of Deposit, 15.9,  Commercial Paper, 15.9,  Cash, 15.3,
Reza
  • 1