Python – Integers String to Integer List
Given an Integers String, composed of negative and positive numbers, convert to integer list.
Input : test_str = ‘4 5 -3 2 -100 -2’
Output : [4, 5, -3, 2, -100, -2]
Explanation : Negative and positive string numbers converted to integers list.
Input : test_str = ‘-4 -5 -3 2 -100 -2’
Output : [-4, -5, -3, 2, -100, -2]
Explanation : Negative and positive string numbers converted to integers list.
Method #1 : Using list comprehension + int() + split()
In this, we split integers using split(), and int() is used for integral conversion. Elements inserted in List using list comprehension
Python3
import string
test_str = '4 5 -3 2 -100 -2 -4 9'
print ( "The original string is : " + str (test_str))
res = [ int (ele) for ele in test_str.split()]
print ( "Converted Integers : " + str (res))
|
Output
The original string is : 4 5 -3 2 -100 -2 -4 9
Converted Integers : [4, 5, -3, 2, -100, -2, -4, 9]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using map() + int()
In this, the task of extension of logic of integer conversion is done using map().
Python3
import string
test_str = '4 5 -3 2 -100 -2 -4 9'
print ( "The original string is : " + str (test_str))
res = list ( map ( int , test_str.split()))
print ( "Converted Integers : " + str (res))
|
Output
The original string is : 4 5 -3 2 -100 -2 -4 9
Converted Integers : [4, 5, -3, 2, -100, -2, -4, 9]
Time Complexity: O(n) -> (average of map function +split)
Auxiliary Space: O(n)
Approach#3:using loop
Algorithm
1.Split the input string using the split() function.
2.Use a loop to convert each string element into an integer and append it to a new list.
Python3
test_str = '4 5 -3 2 -100 -2'
int_list = []
for x in test_str.split():
int_list.append( int (x))
print (int_list)
|
Output
[4, 5, -3, 2, -100, -2]
Time Complexity: O(n), where n is the number of elements in the input string.
Space Complexity: O(n), where n is the number of elements in the input string.
Last Updated :
22 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...