Q:

Python | Convert a string to integers list

belongs to collection: Python List Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

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

# 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

If there is any character except the digits, there will be an error "ValueError: invalid literal 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'

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python List Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Using List as Stack in Python... >>
<< Python | Input comma separated elements, convert i...