Python split string to numbers

Python split string to numbers

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.

Читайте также:  Словари python telegram bot

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.

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.

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

Источник

How to split strings into a list of integers in Python?

List Comprehension is more pythonic way to convert string into a list of int. In this method, we pass a int function to each element of a string of list within a list.

In this method, you need to use str.split() , map() , and list() functions.

   Step-by-step explanation of how these three function works,

We split the string using str.split() function. The syntax for the split function is str.split(separator, maxsplit) .

separator: The separator for the split. The default is a whitespace character. This is optional. maxsplit: Number of splits to output. The default is -1 which outputs all splits. If it is 1, it will give 2 splits.

    Now, convert each element in list into int using the map() function. In above example, the map() passes a int function to all the elements of iterable (list).

The syntax for the map function is map(function, iterable) . The map function returns an object (in Python 3) and hence you need to use the list() function to see the list.

function: Provide any function which will be applied to each element of the iterable such as list iterable: Provide a iterable to apply the function.

Enhance your skills with courses Python

If you enhanced your knowledge and practical skills from this article, consider supporting me on

Buy Me A Coffee

Some of the links on this page may be affiliate links, which means we may get an affiliate commission on a valid purchase. The retailer will pay the commission at no additional cost to you.

Updated: December 12, 2022

Share on

You may also enjoy

Two-Way ANOVA in R: How to Analyze and Interpret Results

Renesh Bedre 2 minute read

This article explains how to perform two-way ANOVA in R

How to Perform One-Way ANOVA in R (With Example Dataset)

Renesh Bedre 1 minute read

This article explains how to perform one-way ANOVA in R

What is Nextflow and How to Use it?

Renesh Bedre 1 minute read

Learn what is Nextflow and how to use it for running bioinformatics pipeline

How to Convert FASTQ to FASTA Format (With Example Dataset)

Renesh Bedre 1 minute read

List of Bioinformatics tools to convert FASTQ file into FASTA format

© 2023 Data science blog. Powered by Jekyll& Minimal Mistakes.

Источник

How To Split A String Into Text And Number In Python

Split a string into text and number in Python

Split a string into Text and Number in Python, that’s the topic I want to introduce to you today. I will show you the functions in the re module that can do this. Hope it helps you.

Split a string into text and number in Python

Use the re.findall function

The re.findall function is excellent for separating text and numbers from a string.

  • regex: regular expression to search for digits.
  • string: string you want the regular expression to search for.

The findall() function returns a list containing the pattern matches in the string. If not found, the function returns an empty list.

  • Import the re module.
  • String initialization.
  • Use re.findall() split a string into text and number.
import re myString = '123learnshareit34website' # Use the re.findall() result = re.findall('(\d+|[A-Za-z]+)', myString) print('Split string into text and numbers:', result)
Split string into text and numbers: ['123', 'learnshareit', '34', 'website']

Use the split() function

Continue to use a re module function, the re.split() function. You can also use it to separate text and numbers from strings.

re.split(RegEx, string, maxsplit)

  • RegEx: are regular expressions.
  • string: string you want to compare.
  • maxsplit: is the maximum number of splits. If not specified, Python defaults to an infinite number of splits.
  • Import the re module.
  • String initialization.
  • Use the re.split() function split string into text and numbers.
import re myString = '123learnshareit34website' # Use the re.split() function result = re.split('(\d+)', myString) print('Split string into text and numbers:', result)
Split string into text and numbers: ['', '123', 'learnshareit', '34', 'website']

Use the groupby() function.

You can combine the three functions in the re library to separate text and numbers from a string.

  • Import the itertools module.
  • Initialize a string.
  • The groupby() function creates an iterator that returns the corresponding tuple (key, group-iterator) by key. The tuple will be handled by the str.isalpha() function.
  • The isalpha() function returns true if the string has at least 1 character and all characters are letters. Otherwise the method will return false.
from itertools import groupby myString = '123learnshareit34website' # Use the itertools.groupby() function result = [''.join(i) for _, i in groupby(myString, str.isalpha)] print('Split string into text and numbers:', result)
Split string into text and numbers: ['123', 'learnshareit', '34', 'website']

Summary

Here are a few Python ways to split a string into text and number in Python. I think you should use the re.findall method. To read more articles, please visit our website to continue. Thanks for reading.

Maybe you are interested:

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.

Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

Источник

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