Python split into integers

Python split into integers

Last updated: Feb 19, 2023
Reading time · 5 min

banner

# Table of Contents

# Split a String into a List of Integers using a list comprehension

To split a string into a list of integers:

  1. Use the str.split() method to split the string into a list of strings.
  2. Use a list comprehension to iterate over the list of strings.
  3. Use the int() class to convert each string to an integer.
Copied!
my_str = '2 4 6 8 10' list_of_strings = my_str.split(' ') print(list_of_strings) # 👉️ ['2', '4', '6', '8', '10'] list_of_integers = [int(x) for x in list_of_strings] print(list_of_integers) # 👉️ [2, 4, 6, 8, 10]

split string into list of integers

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we pass the current list item to the int() class and return the result.

You should also use a list comprehension if you need to split the string on each digit.

Copied!
my_str = '246810' list_of_ints = [int(x) for x in my_str] print(list_of_ints) # 👉️ [2, 4, 6, 8, 1, 0]

We iterate directly over the string and on each iteration, we convert the digit that is wrapped in a string to an integer.

# Handling strings that contain non-digit characters

If your string contains non-digit characters, use the str.isdigit() method to check if the current character is a digit before passing it to the int() class.

Copied!
my_str = 'x y z 2 4 6 8 10 a' list_of_strings = my_str.split(' ') # 👇️ ['x', 'y', 'z', '2', '4', '6', '8', '10', 'a'] print(list_of_strings) list_of_integers = [int(x) for x in list_of_strings if x.isdigit()] print(list_of_integers) # 👉️ [2, 4, 6, 8, 10]

handling strings that contain non digit characters

The str.isdigit method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

# Split a string into a list of integers using map()

This is a three-step process:

  1. Use the str.split() method to split the string into a list of strings.
  2. Use the map() function to convert each string into an integer.
  3. Use the list() class to convert the map object to a list.
Copied!
# 👇️ string containing integers with space-separator my_str = '2 4 6 8 10' list_of_strings = my_str.split(' ') print(list_of_strings) # 👉️ ['2', '4', '6', '8', '10'] list_of_integers = list(map(int, list_of_strings)) print(list_of_integers) # 👉️ [2, 4, 6, 8, 10]

split string into list of integers using map

If your string doesn’t contain a separator between the digits, use the following code sample instead.

Copied!
# 👇️ if you want to split the string on each digit my_str = '246810' list_of_ints = [int(x) for x in my_str] print(list_of_ints) # 👉️ [2, 4, 6, 8, 1, 0]

If the integers in your string are separated with another delimiter, e.g. a comma, pass a string containing a comma to the str.split() method.

Copied!
my_str = '2,4,6,8,10' list_of_strings = my_str.split(',') print(list_of_strings) # 👉️ ['2', '4', '6', '8', '10'] list_of_integers = list(map(int, list_of_strings)) print(list_of_integers) # 👉️ [2, 4, 6, 8, 10]

We used the str.split() method to split the string into a list of strings.

Copied!
my_str = '2 4 6 8 10' list_of_strings = my_str.split(' ') print(list_of_strings) # 👉️ ['2', '4', '6', '8', '10']

The str.split() method splits the string into a list of substrings using a delimiter.

Читайте также:  Добавить рамку html код

The method takes the following 2 parameters:

Name Description
separator Split the string into substrings on each occurrence of the separator
maxsplit At most maxsplit splits are done (optional)

The next step is to convert each string in the list to an integer using the map() function.

Copied!
my_str = '2 4 6 8 10' list_of_strings = my_str.split(' ') print(list_of_strings) # 👉️ ['2', '4', '6', '8', '10'] list_of_integers = list(map(int, list_of_strings)) print(list_of_integers) # 👉️ [2, 4, 6, 8, 10]

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

On each iteration, we pass the string to the int() class to convert it to an integer.

# Split a String into a List of Integers using a for loop

This is a three-step process:

  1. Use the str.split() method to split the string into a list of strings.
  2. Use a for loop to iterate over the list.
  3. Convert each string to an integer and append the result to a new list.
Copied!
my_str = '2 4 6 8 10' list_of_integers = [] for item in my_str.split(' '): list_of_integers.append(int(item)) print(list_of_integers) # 👉️ [2, 4, 6, 8, 10]

split string into list of integers using for loop

We used a for loop to iterate over the result of calling str.split() .

Copied!
my_str = '2 4 6 8 10' # 👇️ ['2', '4', '6', '8', '10'] print(my_str.split(' '))

On each iteration of the for loop, we convert the current string to an integer and append the value to the new list.

The list.append() method adds an item to the end of the list.

# Split a String into a List of Integers using NumPy

You can also use the NumPy module to split a string into a list of integers.

Copied!
import numpy as np my_str = '2 4 6 8 10' my_list = np.fromstring(my_str, dtype=int, sep=' ').tolist() print(my_list) # 👉️ [2, 4, 6, 8, 10]

split string into list of integers using numpy

You can install NumPy by running the following command.

Copied!
pip install numpy # 👇️ or with pip3 pip3 install numpy

The numpy.fromstring method returns a new one-dimensional array initialized from the text in a string.

The method takes a sep argument that is used to determine the split character.

Copied!
import numpy as np my_str = '2,4,6,8,10' my_list = np.fromstring(my_str, dtype=int, sep=',').tolist() print(my_list) # 👉️ [2, 4, 6, 8, 10]

The tolist method converts a numpy array to a list.

Читайте также:  Cut line in html

# Split a String into a List of Integers using re.findall()

You can also use the re.findall() method to split a string into a list of integers.

Copied!
import re my_str = '2 4 6 8 10 12' list_of_strings = re.findall(r'\d+', my_str) print(list_of_strings) # 👉️ ['2', '4', '6', '8', '10', '12'] list_of_ints = [int(x) for x in list_of_strings if x.isdigit()] print(list_of_ints) # 👉️ [2, 4, 6, 8, 10, 12]

split string into list of integers using re findall

The re.findall method takes a pattern and a string as arguments and returns a list of strings containing all non-overlapping matches of the pattern in the string.

The first argument we passed to the re.findall() method is a regular expression.

The \d character matches the digits from 0 to 9 (and many other digit characters).

The plus + causes the regular expression to match 1 or more repetitions of the preceding character (the range of numbers).

The re.findall() method returns a list containing the matches as strings.

The last step is to use a list comprehension to convert the list of strings to a list of numbers.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Python split into integers

Last updated: Feb 20, 2023
Reading time · 3 min

banner

# Table of Contents

# Split a Float into Integer and Decimal parts in Python

Use the math.modf() method to split a number into integer and decimal parts.

The math.modf() method returns the fractional and integer parts of the provided number.

Copied!
import math my_num = 1.3588 result = math.modf(my_num) print(result) # 👉️ (0.3588, 1.0) print(result[0]) # 👉️ 0.3588 print(result[1]) # 👉️ 1.0

You can also use unpacking to assign the decimal and integer parts to variables.

Copied!
import math my_num = 1.3588 dec, integer = math.modf(my_num) print(dec) # 👉️ 0.3588 print(integer) # 👉️ 1.0

We used the math.modf() method to split a number into integer and decimal parts.

The math.modf method returns the fractional and integer parts of the provided number.

# The fractional and integer parts are of type float

The fractional and integer parts carry the sign of the provided number and are floats.

Copied!
import math my_num = -1.3588 result = math.modf(my_num) print(result) # 👉️ (-0.3588, -1.0) print(result[0]) # 👉️ -0.3588 print(result[1]) # 👉️ -1.0 # ----------------------------------------- # ✅ unpack decimal and integer values dec, integer = result print(dec) # 👉️ -0.3588 print(integer) # 👉️ -1.0

Notice that both of the values in the tuple are floats.

# Converting the integer part to an int after splitting

Copied!
import math my_num = 1.3588 result = math.modf(my_num) print(result) # 👉️ (0.3588, 1.0) dec = result[0] print(dec) # 👉️ 0.3588 integer = int(result[1]) print(integer) # 👉️ 1

Alternatively, you can use the % operator and floor division // .

# Split a number into integer and decimal parts using modulo operator

This is a two-step process:

  1. Use floor division to get the integer part of the number by dividing by 1 , e.g. num // 1 .
  2. Use the modulo % operator to get the fractional part by getting the remainder after dividing by 1 , e.g. num % 1 .
Copied!
my_num = -1.3588 dec = my_num % 1 print(dec) # 👉️ 0.3588 integer = my_num // 1 print(integer) # 👉️ 1.0

The modulo (%) operator returns the remainder from the division of the first value by the second.

Читайте также:  Найти среднее арифметическое чисел массива питон

When we use the modulo operator to divide a number by 1 , the remainder is the fractional part.

Copied!
print(1.3588 % 1) # 👉️ 0.3588

You can use floor division to get the integer part of a number.

Copied!
my_num = -1.3588 integer = my_num // 1 print(integer) # 👉️ 1.0 dec = my_num % 1 print(dec) # 👉️ 0.3588

The result of using the floor division // operator is that of a mathematical division with the floor() function applied to the result.

Dividing a number by 1 and rounding down, gives us the integer part of the number.

However, if you decide to use this approach, note that it doesn’t handle negative numbers as you would expect.

Copied!
my_num = -1.3588 dec = my_num % 1 print(dec) # 👉️ 0.6412 integer = my_num // 1 print(integer) # 👉️ -2.0

If you have to handle negative numbers, use the math.modf() method instead.

# Split a number into integer and decimal parts using divmod

You might also see examples online that use the divmod() function.

However, note that divmod() also doesn’t handle negative numbers in a way you would expect.

Copied!
my_num = 1.3588 result = divmod(my_num, 1) print(result) # 👉️ (1.0, 0.3588) integer = int(result[0]) print(integer) # 👉️ 1 dec = result[1] print(dec) # 👉️ 0.3588

The divmod function takes two numbers and returns a tuple containing 2 values:

  1. The result of dividing the first argument by the second.
  2. The remainder of dividing the first argument by the second.

However, the divmod() function also doesn’t handle negative numbers in a way that suits our use case.

Copied!
my_num = -1.3588 result = divmod(my_num, 1) print(result) # 👉️ (-2.0, 0.6412) integer = int(result[0]) print(integer) # 👉️ -2 dec = result[1] print(dec) # 👉️ 0.6412

For this reason, you should use the math.modf() method when you have to split a number into integer and decimal parts.

# Subtracting integers from floats and accuracy

You can also split a floating-point number to an integer by:

  1. Converting the float to an integer (to drop the decimal).
  2. Subtracting the integer from the float to get the decimal part.
Copied!
a_float = 1.03588 integer = int(a_float) print(integer) # 👉️ 1 dec = a_float - integer print(dec) # 👉️ 0.03587999999999991

However, notice that you might get surprising results when subtracting from a floating-point number.

The resulting number cannot be represented in binary, so the precision is lost.

This might or might not suit your use case.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

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