How to get the first numbers from a string?
Example: I have "1567438absdg345"
I only want to get "1567438" without "absdg345", I want it to be dynamic, get the first occurrence of Alphabet index and remove everything after it.
Making use of isdigit() function to extract digits from a Python string. Python provides us with string. isdigit() to check for the presence of digits in a string. Python isdigit() function returns True if the input string contains digit characters in it.
To get the first digit, we can use the Python math log10() function. In the loop example, we divided by 10 until we got to a number between 0 and 10. By using the log10() function, we can find out exactly how many times we need to divide by 10 and then do the division directly.
To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.
You can use the TakeWhile
extension methods to get characters from the string as long as they are digits:
string input = "1567438absdg345"; string digits = new String(input.TakeWhile(Char.IsDigit).ToArray());
The Linq approach:
string input = "1567438absdg345"; string output = new string(input.TakeWhile(char.IsDigit).ToArray());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With