![]() |
|
[Tut] How To Extract Numbers From A String In Python? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How To Extract Numbers From A String In Python? (/thread-100801.html) |
[Tut] How To Extract Numbers From A String In Python? - xSicKxBot - 02-26-2023 How To Extract Numbers From A String In Python? 5/5 – (4 votes) The easiest way to extract numbers from a Python string Code: sCode: re.findall('\d+', s)Code: re.findall('\d+', 'hi 100 alice 18 old 42')Code: ['100', '18', '42']Code: int()Code: float()There are some tricks and alternatives, so keep reading to learn about them. ![]() In particular, you’ll learn about the following methods to extract numbers from a given string in Python:
Problem Formulation ![]() Extracting digits or numbers from a given string might come up in your coding journey quite often. For instance, you may want to extract certain numerical figures from a CSV file, or you need to separate complex digits and figures from given patterns. Having said that, let us dive into our mission-critical question: Problem: Given a string. How to extract numbers from the string in Python? Example: Consider that you have been given a string and you want to extract all the numbers from the string as given in the following example: Given is the following string: Code: s = 'Extract 100, 1000 and 10000 from this string'This is your desired output: Code: [100, 1000, 10000]Let us discuss the methods that we can use to extract the numbers from the given string: Method 1: Using Regex Module ![]() The most efficient approach to solving our problem is to leverage the power of the Code: reCode: RegExThus to solve our problem, we must import the Code: regexCode: findall()◈ Learn More: Code: re.findall()Code: re.findall()Let us have a look at the following code to understand how we can use the Code: regexCode: import re sentence = 'Extract 100 , 100.45 and 10000 from this string'
s = [float(s) for s in re.findall(r'-?\d+\.?\d*', sentence)]
print(s)Output Code: [100.0, 100.45, 10000.0]This is a Python code that uses the Code: reCode explanation: ![]() The line Code: s = [float(s) for s in re.findall(r'-?\d+\.?\d*', sentence)]Code: re.findall()Code: reCode: sentenceSpecifically, it looks for strings of characters that match the regular expression pattern Code: r'-?\d+.?\d*'The Code: re.findall()The list comprehension Code: [float(s) for s in re.findall(r'-?\d+\.?\d*', sentence)]Code: findallCode: float()Code: s Recommended: Python List ComprehensionMethod 2: Split and Append The Numbers To A List using split() and append() Another workaround for our problem is to split the given string using the Code: split()Code: float()Note:
Now that we have the necessary tools to solve our problem based on the above concept let us dive into the code to see how it works: Code: sentence = 'Extract 100 , 100.45 and 10000 from this string' s = []
for t in sentence.split(): try: s.append(float(t)) except ValueError: pass
print(s)Output Code: [100.0, 100.45, 10000.0]Another approach to solving our problem is to use the Code: isdigit()The Code: isdigit()Code: TrueCode: FalseLet us have a look at the code given below to see how the above concept works: Code: sentence = 'Extract 100 , 100.45 and 10000 from this string'
s = [int(s) for s in str.split(sentence) if s.isdigit()]
print(s)Output Code: [100, 10000] Alert! This technique is best suited to extract only positive integers. It won’t work for negative integers, floats, or hexadecimal numbers.Method 4: Using Numbers from String Library This is a quick hack if you want to avoid spending time typing explicit code to extract numbers from a string. You can import a library known as Code: nums_from_stringSince the Code: nums_from_stringCode: pip install nums_from_stringThe following program demonstrates the usage of Code: nums_from_stringCode: import nums_from_string sentence = 'Extract 100 , 100.45 and 10000 from this string'
print(nums_from_string.get_nums(sentence))Output Code: [100.0, 100.45, 10000.0]Thus from the above discussions, we found that there are numerous ways of extracting a number from a given string in python. My personal favorite, though, would certainly be the regex module Code: reYou might argue that using other methods like the Code: isdigit()Code: split()Code: '25.50k'Furthermore, speed is kind of an irrelevant metric when it comes to log parsing. Now you see why regex is my personal favorite in this list of solutions. If you are not very supportive of the Code: re![]() ![]() I hope you found this article useful and added some value to your coding journey. Please stay tuned for more interesting stuff in the future. |