Home » Python » Python programs

Python | Convert a string to integers list

Here, we will learn how to convert a string (that contains digits only) to the integers list in Python?
Submitted by IncludeHelp, on September 19, 2018

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.

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'





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.