Given a string with digits and we have to convert the string to its equivalent 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 only digits between 0 to 9, if there is any character except digits, the program will through a ValueError.
How to convert character (only digit) to integer?
To convert a character (that is digit only like: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9') to integer, we use int() function - which is a library function in Python. int() returns integer value equivalent to given character i.e. digit in character form.
Output
Python program to convert a string to integers list
Here, we have a string "12345" and we are converting it to integers list [1, 2, 3, 4, 5].
Output
ValueError
If there is any character except the digits, there will be an error "ValueError: invalid literal for int() with base 10".
Program with Error:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer