Python | Convert a string to integers list

Python | String to List of Integers Conversion: In this tutorial, we will learn how to convert a given string that contains digits only to the integers list in Python. By IncludeHelp Last updated : June 25, 2023

Problem statement

Given a string with digits and we have to convert the string to its equivalent list of integers in Python.

Example

Consider the below example with sample input/output values -

Input:
str1 = "12345"
Output:
int_list = [1, 2, 3, 4, 5]

Input:
str1 = "12345ABCD"
Output:
ValueError

String to list of integers conversion in Python

Note: The string must contain only digits between 0 to 9, if there is any character except digits, the program will through a ValueError.

1. Iterate string, convert to int, and append to the list

In this approach, we will iterate the string using the for ... in loop, convert each character to its equivalent integer value using the int() function, and append the integer to the list using the list.append() method. Finally, you will get a list of integers.

Example

# Program to convert string to integers list

# Declare a string
str1 = "12345"

# Print string
print("Original string (str1): ", str1)

# List to store integers
int_list = []

# Iterate string, convert characters to
# integers, and append into the list
for ch in str1:
    int_list.append(int(ch))

# Print the list
print("List of integers: ", int_list)

Output

Original string (str1):  12345
List of integers:  [1, 2, 3, 4, 5]

2. Using list comprehension

In this approach, we will iterate the string and convert each character to its equivalent integer using list comprehension.

Example

# Convert string to integers list
# string
str1 = "12345"

# Print string
print("Original string (str1): ", str1)

# list comprehension
int_list = [int(x) for x in str1]

# Print the list
print("List of integers: ", int_list)

Output

Original string (str1):  12345
List of integers:  [1, 2, 3, 4, 5]

3. Using list comprehension by handling non-digit characters in the string

If there are non-digit characters in the string, you can use the str.isdigit() method before converting the character to an integer.

Example

# Convert string to integers list
# string
str1 = "Hello12345"

# Print string
print("Original string (str1): ", str1)

# list comprehension
int_list = [int(x) for x in str1 if x.isdigit()]

# Print the list
print("List of integers: ", int_list)

Output

Original string (str1):  Hello12345
List of integers:  [1, 2, 3, 4, 5]

Python List Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.