简体   繁体   中英

Python split a string then regex

I'm kinda stuck on a basic probleme but I really need your help here. Here I get a sentence from an rss feed where I want to extract the grade which is either at the end or non existant grades = thefeedentry.get("title", "").split(" ") So I split it and here is what I get: ['Séance1', ':', '9.25/20'] and now I need to get the '9,25' and I think that I should do it using regex so I used grades as an array:

for grade in grades
                x = re.findall("/20$", grade)
                print(x)

and here I get an error without any specification:/ I think that it come from my for loop but I'm stuck and it since a while

This can help you.

import re
title = "Seance1' : 9.25/20"
re.search(r'(?<=(\:\s))[\d\.]+(?=[\/])', title).group()

Regex demo

To get the number from the list you provided, just get the last item and split with / and grab the first item:

print ( grades[-1].split('/')[0] )

You may extract the number between : and / with the regex directly from your string:

import re
text = "Séance1 : 9.25/20"
m = re.search(r':\s*(\d[\d.]*)/', text)
if m:
    print ( m.group(1) )

See the Python demo . You may add logic to handle a case when the number is not found.

Regex details

  • : - a colon
  • \s* - 0+ whitespaces
  • (\d[\d.]*) - Group 1: a digit and then 0 or more digit or . chars
  • / - a / char.

See the regex demo .

There is no need for Regex here.

This should work..

grades[-1].split('/')[0]

Here we try to get the values at last index of ['Séance1', ':', '9.25/20'] ie 9.25/10

 grades[-1]

We split the 9.25/10 on occurrence of '/' by using split function so we get [9.25, 10].

split('/') 

Then we select 0th index of the previous step, hence we get 9.25.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM