String of int to list python
Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the entire list of strings to integers is quite common in the development domain. Let’s discuss a few ways to solve this particular problem. Show
Method 1: Using eval()Python eval() function parse the expression argument and evaluate it as a python expression and runs Python expression(code), If the expression is an int representation, Python converts the argument to an integer. Python3
Output: Modified list is: [1, -4, 3, -6, 7] Method 2: Naive MethodThis is the most generic method that strikes any programmer while performing this kind of operation. Just looping over the whole list and converting each string of the list to int by type casting. Python3
Output: Modified list is: [1, 4, 3, 6, 7] Method 3: Using list comprehensionThis is just a kind of replica of the above method, just implemented using list comprehension, a kind of shorthand that a developer looks for always. It saves the time and complexity of coding a solution. Python3
Output: Modified list is : [1, 4, 3, 6, 7] Method 4: Using map()This is the most elegant, pythonic, and recommended method to perform this particular task. This function is exclusively made for this kind of task and should be used to perform them. Python3
Output: Modified list is : [1, 4, 3, 6, 7] Method 5: List of strings with mixed integer representationsHere, we will first convert each string to a float first and then we will convert it into an integer by using the round() function, otherwise, it will through error. Python3
Output: Modified list is: [1, 4, 4, 7, 7] Split on commas, then map to integers:
Or use a list comprehension:
The latter works better if you want a list result, or you can wrap the This works because
Splitting on just a comma also is more tolerant of variable input; it doesn't matter if 0, 1 or 10 spaces are used between values. How do you turn a string of numbers into a list of integers in Python?The most Pythonic way to convert a list of strings to a list of ints is to use the list comprehension [int(x) for x in strings] . It iterates over all elements in the list and converts each list element x to an integer value using the int(x) built-in function.
Can you convert a string to a list in Python?Python String is a sequence of characters. We can convert it to the list of characters using list() built-in function. When converting a string to list of characters, whitespaces are also treated as characters. Also, if there are leading and trailing whitespaces, they are part of the list elements too.
Can we convert integer to list in Python?Use map() to convert an integer to a list. Call str(x) on an integer x to convert it to a string. Use map(function, iterable) with the string from the previous step as iterable and int as function to apply the function int() on each digit in the string.
|