0

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.

5
  • Try: id = [int(i) for i in url if i.isdigit()] Commented Apr 1, 2022 at 17:18
  • url.split() will return the whole url, due to the string not containing any whitespaces. Did you mean to try url.split("/")? Commented Apr 1, 2022 at 17:18
  • @HampusLarsson I did, but still I am getting []. Commented Apr 1, 2022 at 17:19
  • [int(i) for i in url.split("/") if i.isdigit()] returns [1987] for me though, are you sure that you're not running the old unchanged code? Commented Apr 1, 2022 at 17:20
  • @HampusLarsson your last solution is working. Commented Apr 1, 2022 at 17:22

3 Answers 3

1

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']

Sign up to request clarification or add additional context in comments.

Comments

0

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

import re

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

See live demo.

Comments

0

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('/').

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.