-1

Is there a build-in function of Python to get the number of a string?

I have a type of string like this '20180318_beta'.

I want to get the 20180318 of it, so is there a build-in method for achieving this?

sof-03
  • 2,255
  • 4
  • 15
  • 33
  • this will do int(filter(str.isdigit, str1)) from [here](https://stackoverflow.com/questions/26825729/extract-number-from-string-in-python/26825781) – Nidhin Sajeev Jul 28 '18 at 03:24
  • If it's always number followed by underscore, do `int(mystring.split("_")[0])` – pault Jul 28 '18 at 03:29
  • @NidhinSajeev: This assumes no digit are separated from the main block of numbers required (a string like `'20180318_beta2'` would be parsed as `201803182`, which is probably not the intention). Also, using `filter` (without wrapping with `''.join()` to convert the `filter` iterator back to a `str`) will only work on Python 2. – ShadowRanger Jul 28 '18 at 03:31
  • @ShadowRanger ok but here he want to Extract numbers from a string only – Nidhin Sajeev Jul 28 '18 at 03:33

2 Answers2

1

Here is a list of built in functions: https://docs.python.org/3/library/functions.html

As you can see, there is no specific function for what you are asking. However, if you wanted to build a function for it, there are many questions you have to ask yourself. Can it handle negatives? Can you find non-integers? What about numbers in different places?

You can always use regex to attempt this problem. Here is a previous post about it: Python: Extract numbers from a string

If all of your cases will be similar to the one above, you can always use the split method. In other cases, I would refer to this post: Extract Number from String in Python

Just as a side note, if you do use the last link, be careful with the top answer with Python 3.x as the filter function is slightly different than its counterpart.

SamrajM
  • 620
  • 5
  • 12
0

Well depending on the robustness you require, casting to int will work in this case because your string starts with numbers. However, If it started with a letter it would fail.

It's pretty simple to roll your own, see this stack overflow answer.

Python parse int from string

Collin Craige
  • 109
  • 1
  • 8
  • 1
    "Casting" to `int` won't work; `int('20180318_beta')` will raise a `ValueError`; `int` is for strings composed solely of valid digits, with optional leading and trailing whitespace (which is ignored). – ShadowRanger Jul 28 '18 at 03:28