Max Cha
Max Cha

Reputation: 31

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

Upvotes: 2

Views: 215

Answers (3)

Karmveer Singh
Karmveer Singh

Reputation: 953

This can help you.

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

Regex demo

Upvotes: 1

Rohan Kanade
Rohan Kanade

Reputation: 51

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'] i.e. 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.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626728

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.

Upvotes: 1

Related Questions