Python get only numbers

How to Get Only Numbers from a List in Python?

I am going to show you an example of get integer only values from a list in python. This article goes in detailed on python get only numbers from list. I am going to show you about how to get only integer value from list in python. This article goes in detailed on how to get only numbers from a list in python. Alright, let us dive into the details.

If you have list in python with numeric and non-numeric values in list and you want to get only numeric values from list in python, then there are several ways to do that. i will give you simple two examples here using comprehension with isinstance() and isdigit() functions. so, let’s see the following examples:

You can use these examples with python3 (Python 3) version.

let’s see below a simple example with output:

# Create New List with Item myList = ["a", 1, 2, "b", "c", 4, 5, "d"] # Get integer only values from a list in Python newList = [val for val in myList if isinstance(val, (int, float))] print(newList)
# Create New List with Item myList = ["a", "1", "2", "b", "c", "4", "5", "d"] # Get integer only values from a list in Python newList = [val for val in myList if val.isdigit()] print(newList)

Hardik Savani

I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

Читайте также:  Комментарий строки в php

We are Recommending you

  • How to Get Only Positive Values in Python List?
  • Python List Get All Items Less Than Some Value Example
  • Python List Get All Elements Greater Than Some Value Example
  • Python Convert List to String with Space Example
  • How to Get Last n Elements of a List in Python?
  • How to Get First n Elements of a List in Python?
  • How to Get First 2, 3, 4, 5, 10, etc Elements from List in Python?
  • How to Convert List to Capitalize First Letter in Python?
  • How to Convert List to Uppercase in Python?
  • Python Convert List into String with Commas Example
  • How to Convert List to Lowercase in Python?
  • Python Split String into List of Characters Example
  • Python Remove Empty String from List Example

Источник

Extract Numbers From String in Python

In this tutorial, we will look at how to extract numbers from a string in Python with the help of examples.

How to extract numbers from string?

Extract numbers from string in python

You can iterate through the string and use the string isdigit() function to extract numbers from a string in Python. Use the following steps –

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

  1. Intialize our resulting string to an empty string.
  2. Iterate through the string.
  3. For each character in the string, use the isdigit() function to check if its a digit or not.
  4. If it is a digit, add the character to our result string.

Let’s look at an example to see the above steps in action in Python.

# string with numbers s = "I love you 3000" # result string s_nums = "" # iterate over characters in s for ch in s: if ch.isdigit(): s_nums += ch # display the result string print(s_nums)

The resulting string contains only digits from the original string.

You can reduce the above code to a single line by using a list comprehension and the string join() function.

# string with numbers s = "I love you 3000" # result string s_nums = "".join([ch for ch in s if ch.isdigit()]) # display the result string print(s_nums)

We get the same result as above. The resulting string only contains numerical characters. Here, we use a list comprehension to get a list numerical characters in the string. We then use the string join() function to join these characters back to a string.

Note that this method will only capture the digits in the string. For example, if the string contains negative numbers, this method will only capture the digits and not the sign.

# string with numbers s = "The temperature is -5 degrees celsius." # result string s_nums = "".join([ch for ch in s if ch.isdigit()]) # display the result string print(s_nums)

Here, we get the digit in the string in our resulting string but we don’t get the sign for the negative number.

Using regular expressions to extract numbers from string

Alternatively, you can use regular expressions to extract numbers from a string. Let’s use it to capture the digits in a string.

import re # string with numbers s = "I love you 3000" # result list s_nums = re.findall(r'\d', s) # display the result list print(s_nums) print("".join(s_nums))

We get the numbers from the string in our result list. You can also capture contiguous digits using the r’\d+’ regular expression.

A good thing about using regular expressions is that you can customize them to capture patterns relevant to you. For example, if you also want to capture negative integers (with sign) you can use the regular expression, r’-?\d+’

import re # string with numbers s = "The temperature on the 27th of December was -5 degrees celsius." # result list s_nums = re.findall(r'-?\d+', s) # display the result list print(s_nums)

We get the numbers in the string along with the negative sign (if present) in our result list.

You might also be interested in –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

2 Easy Ways to Extract Digits from a Python String

Ways To Extract Digits From A String

Hello, readers! In this article, we will be focusing on the ways to extract digits from a Python String. So, let us get started.

1. 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.

We need not pass any parameter to it. As an output, it returns True or False depending upon the presence of digit characters in a string.

inp_str = "Python4Journaldev" print("Original String : " + inp_str) num = "" for c in inp_str: if c.isdigit(): num = num + c print("Extracted numbers from the list : " + num)

In this example, we have iterated the input string character by character using a for loop. As soon as the isdigit() function encounters a digit, it will store it into a string variable named ‘num’.

Thus, we see the output as shown below–

Original String : Python4Journaldev Extracted numbers from the list : 4

Now, we can even use Python list comprehension to club the iteration and idigit() function into a single line.

By this, the digit characters get stored into a list ‘num’ as shown below:

inp_str = "Hey readers, we all are here be 4 the time!" print("Original string : " + inp_str) num = [int(x) for x in inp_str.split() if x.isdigit()] print("The numbers list is : " + str(num))
Original string : Hey readers, we all are here be 4 the time! The numbers list is : [4]

2. Using regex library to extract digits

Python regular expressions library called ‘regex library‘ enables us to detect the presence of particular characters such as digits, some special characters, etc. from a string.

We need to import the regex library into the python environment before executing any further steps.

Further, we we re.findall(r’\d+’, string) to extract digit characters from the string. The portion ‘\d+’ would help the findall() function to detect the presence of any digit.

import re inp_str = "Hey readers, we all are here be 4 the time 1!" print("Original string : " + inp_str) num = re.findall(r'\d+', inp_str) print(num)

So, as seen below, we would get a list of all the digit characters from the string.

Original string : Hey readers, we all are here be 4 the time 1! ['4', '1']

Conclusion

By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.

I recommend you all to try implementing the above examples using data structures such as lists, dict, etc.

For more such posts related to Python, Stay tuned and till then, Happy Learning!! 🙂

Источник

Check If a List Contains Only Numbers in Python

In this tutorial, we will look at how to check if a list contains only numbers in Python with the help of some examples.

How to check if all list elements are numbers?

Check if list contains only numbers in python

You can use a combination of the Python built-in isinstance() and all() function to check if a list contains only numbers. For instance, you can use the following steps to check if all elements in a list are integers in Python –

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

  1. In a list comprehension, for each element in the list, check if it’s an integer using the isinstance() function.
  2. Apply the Python built-in all() function to return True only if all the items in the above list comprehension correspond to True .

The following is the code to check if all elements in a list are integers or not.

# check if all elements in ls are integers all([isinstance(item, int) for item in ls])

Let’s take a look at an example.

# list of numbers ls = [1, 2, 3, 4] # check if list contains only numbers print(all([isinstance(item, int) for item in ls]))

We get True as the output as all elements in the list ls are integers.

Let’s take a look at another example.

# list of numbers and a string ls = [1, 2, 3, 4, 'cat'] # check if list contains only numbers print(all([isinstance(item, int) for item in ls]))

Here we get False as the output because not all elements in the list ls are integers. One element, “cat” in the list is a string.

Check if all items in a list of strings are numeric

If you, however, have a list of strings and want to check whether all the elements in the list are digits or not, you can use the following code.

# list of numeric strings ls = ["1", "2", "3", "4"] # check if list of string contains only numberic elements print(all([item.isdigit() for item in ls]))

Here we check whether each element in the list of strings, ls is a numerical value or not using the string isdigit() function. We get True as the output as all the strings in the list ls are numeric characters.

You might also be interested in –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

Оцените статью