Home > Back-end >  Get number from string in Python
Get number from string in Python

Time:04-02

I have a string, I have to get digits only from that string.

 url = "www.mylocalurl.com/edit/1987"

Now from that string, I need to get 1987 only. I have been trying this approach,

id = [int(i) for i in url.split() if i.isdigit()]

But I am getting [] list only.

CodePudding user response:

You can use regex and get the digit alone in the list.

import re
url = "www.mylocalurl.com/edit/1987"
digit = re.findall(r'\d ', url) 

output:

['1987']

CodePudding user response:

Replace all non-digits with blank (effectively "deleting" them):

import re

num = re.sub('\D', '', url)

See live demo.

CodePudding user response:

You aren't getting anything because by default the .split() method splits a sentence up where there are spaces. Since you are trying to split a hyperlink that has no spaces, it is not splitting anything up. What you can do is called a capture using regex. For example:

import re
url = "www.mylocalurl.com/edit/1987"
regex = r'(\d )'
numbers = re.search(regex, url)
captured = numbers.groups()[0]

If you do not what what regular expressions are, the code is basically saying. Using the regex string defined as r'(\d )' which basically means capture any digits, search through the url. Then in the captured we have the first captured group which is 1987.

If you don't want to use this, then you can use your .split() method but this time provide a split using / as the separator. For example `url.split('/').

  • Related