Here, we will figure out how to change over a string (that contains digits just) to the integers list in Python?
Given a string with digits and we need to change over the string to its equal list of the integers in Python.
Example:
Input:
str1 = "12345"
Output:
int_list = [1, 2, 3, 4, 5]
Input:
str1 = "12345ABCD"
Output:
ValueError
Note: The string must contain just digits between 0 to 9, if there is any character aside from digits, the program will through a ValueError.
How to change over the character (just digit) to an integer?
To change over a character (that is digit just like: ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’) to integer, we use int() work – which is a library work in Python.
int() returns integer value proportional to given character for example digit in character structure.
print (int('0'))
print (int('1'))
print (int('2'))
print (int('3'))
print (int('4'))
print (int('5'))
print (int('6'))
print (int('7'))
print (int('8'))
print (int('9'))
Output:
0
1
2
3
4
5
6
7
8
9
Python program to change over a string to integers list:
Here, we have a string “12345” and we are changing over it to integers list [1, 2, 3, 4, 5].
# program to convert string to integer list
# language: python3
# declare a list
str1 = "12345"
# list variable to integeres
int_list =[]
# converting characters to integers
for ch in str1:
int_list.append(int(ch))
# printing the str_list and int_list
print ("str1: ", str1)
print ("int_list: ", int_list)
Output:
str1: 12345
int_list: [1, 2, 3, 4, 5]
ValueError
On the off chance that there is any character aside from the digits, there will be a blunder “ValueError: invalid exacting for int() with base 10”.
Program with Error:
# program to convert string to integer list
# language: python3
# declare a list
str1 = "12345ABCD"
# list variable to integeres
int_list =[]
# converting characters to integers
for ch in str1:
int_list.append(int(ch))
# printing the str_list and int_list
print ("str1: ", str1)
print ("int_list: ", int_list)
Output:
Traceback (most recent call last):
File "/home/main.py", line 12, in
int_list.append(int(ch))
ValueError: invalid literal for int() with base 10: 'A'