在Python中使用十进制数字和一些字符分割字符串

时间:2020-08-22 18:15:07

标签: python

我有一个字符串,例如:“国库券52.9存单15.9商业票据15.9现金15.3”

我想将它们分为两部分:数字部分和非数字部分。例如:“国库券”,“ 52.9”。

我想知道如何在Python中做到这一点。

2 个答案:

答案 0 :(得分:0)

您可以尝试进行正则表达式匹配,以查找字母和空格以及十进制数字。

例如:

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)

输出:

['Treasury Notes', '52.9', 'Certificates Of Deposit', '15.9', 'Commercial Paper', '15.9', 'Cash', '15.3']

答案 1 :(得分:0)

如果需要字符串结果,可以执行以下操作:

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}"

输出:

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