Home > Software engineering >  Only join number until hit any latter in python using join
Only join number until hit any latter in python using join

Time:03-30

string = "buy @ 1890 . 00 and exit $700" If the string contains @ then split the string using @. Then take the last split item and only join the number until join hits the letter not the number.

price = ''.join(c for c in string.replace(" ","").split("@")[-1] if (c.isdigit() or c=="." ))

but it retunes 1890.00700, not 1890.00

desire output only 1890.00, not 1890.00700

CodePudding user response:

If you are open to using regex, re.findall might work well here:

string = "buy @ 1890 . 00 and exit $700"
nums = re.findall(r'@\s*([0-9. ] )\b', string)
print(nums)  # ['1890 . 00']
  • Related