Maciej
Maciej

Reputation: 133

Is there any way to write it better?

i have a code like this:

page_number = re.sub('[^0-9]', '', total_matches)
page_number = int(page_number) + 1

Is there any way to write it better? I mean something like that:

x = 5
x += 5

Upvotes: 0

Views: 70

Answers (2)

Igor Pejic
Igor Pejic

Reputation: 3698

One liner:

page_number = int(re.sub('[^0-9]', '', total_matches)) + 1

Upvotes: 2

Matthias
Matthias

Reputation: 13222

Change the place where int is called.

page_number = int(re.sub('[^0-9]', '', total_matches))
page_number += 1

If it isn't guaranteed that there is always a page number you can catch the exception.

try:    
    page_number = int(re.sub('[^0-9]', '', total_matches))
except ValueError:
    page_number = 0
page_number += 1

Now it's longer but more robust.

Upvotes: 0

Related Questions