Summary: You can split a string and convert it to integer values by either using a list comprehension or Python’s built-in
phone = '91-9567-123456' # Method 1 print(list(map(int, phone.split('-')))) # OUTPUT: [91, 9567, 123456] # Method 2 print([int(x) for x in phone.split("-")]) # OUTPUT: [91, 9567, 123456]
📜Problem: Given a string containing integers separated by a specific delimiter. How will you split the string using the given delimiter and store the integer strings into a list. Note that the items in the resultant list should be integers and not strings.
Example: Consider that you have been given an IP address as the string. Extract each number from the given IP and store them in a list using “.” as the delimiter.
Given: ip = "220.127.116.11" Expected Output: [192, 158, 1, 38]
Now that we have an overview of our problem, let us dive into the methods without any further ado.
Method 1: Using List Comprehension
Prerequisite: List comprehension is a compact way of creating lists. The simple formula is [expression + context].
– Expression: What to do with each list element?
– Context: What elements to select? The context consists of an arbitrary number of for and if statements.
[x for x in range(3)] creates the list
[0, 1, 2].
🌎Read more here: List Comprehension in Python — A Helpful Illustrated Guide
Approach: You can use the
split(".") function to split the given string using the given delimiter “
.” which stores the split string as items in a list. Then use a for loop to iterate over the split strings which are stored as items in a list and typecast them into integer values one by one. All of this can be done in a single line using a list comprehension.
ip = "18.104.22.168" res = [int(x) for x in ip.split(".")] print(res) # [192, 158, 1, 38]
Method 2: Using map
Approach: In this method, we will use Python’s built-in
map() function. Initially we have to split the string using the
split() function at the given delimiter which is “.” in this case. This will give us a list containing the split strings. This list serves as the iterator argument within the
map function and each split string is then passed the integer function contained within the
map method as the first argument. The
int function allows you to convert the split strings to integer values. The map function returns a map object which can be converted into a list and displayed as the final output.
ip = "22.214.171.124" res = list(map(int, ip.split('.'))) print(res) # [192, 158, 1, 38]
map() function transforms one or more iterables into a new one by applying a “transformator function” to the i-th elements of each iterable. The arguments are the transformator function object and one or more iterables. If you pass n iterables as arguments, the transformator function must be an n-ary function taking n input arguments. The return value is an iterable map object of transformed, and possibly aggregated, elements.
🌎Read more here: Python map() — Finally Mastering the Python Map Function [+Video]
A Quick Comparison Between The Two Methods Used
Let’s run a quick test on both the methods to test the efficiency of the two functions. The quick test code as shown below indicates that
map() function wins the race in terms of efficiency regarding the time taken to complete the operation (building a list of integers from a value-splitted string).
However, using list comprehension method to split a string and convert into integers is a more lucid and easy to understand approach. Also, it does not involve the usage of complex built-in functions like
map() which can often be daunting for beginners.
import time ip = "126.96.36.199" start = time.time() res_1 = [int(x) for x in ip.split(".")] time.sleep(2) print(res_1) end = time.time() print(end - start) start = time.time() res_2 = list(map(int, ip.split('.'))) time.sleep(2) print(res_2) end = time.time() print(end - start)
[192, 158, 1, 38] 2.0009641647338867 [192, 158, 1, 38] 2.00071382522583
Note: The difference in time taken between the two functions is negligible. Hence, it does not matter much unless the input data is very large.
💎Python Split String by Space and Convert to Int
Challenge: Given a string containing integers separated by space. How will you split the string using space as the given delimiter ” ” and store the integer strings into a list?
# Input x = '1 2 3 4 56 78 9' # Expected Output [1, 2, 3, 4, 56, 78, 9]
x = '1 2 3 4 56 78 9' res = list(map(int, x.split(' '))) print(res)
💎Python Split String by Comma and Convert to Int
Challenge: Given a string containing integers separated by comma. How will you split the string using the given delimiter “
,” and store the integer strings into a list.
# Input: no = '3,77,400' # Expected Output: [3, 77, 400]
no = '3,77,400' res = list(map(int, no.split(','))) print(res)
We have successfully solved the given problem using different approaches. I hope this article helped you in your Python coding journey. Please subscribe and stay tuned for more interesting articles and solutions. Happy Coding!
🌎Recommended Read: How to Convert a String List to an Integer List in Python