No matter which method you choose, be sure to check that your string list contains only valid integers, otherwise the conversion will fail and result in a ValueError. The resulting values are appended to a new list called integer_list. Here, we use a for loop to iterate over each element in the string_list, and use the int() function to convert it to an integer. Some quick testing on my Python 2.6 install indicates map is probably the most efficient candidate here (building a list of integers from a value-splitted string). The resulting values are then passed to the list() function to create a new list of integers. test '8743-12083-15' lstint int(x) for x in test.split('-') EDIT: As to which is most efficient (cpu-cyclewise) is something that should always be tested. In this example, we use the map() function to apply the int() function to each element in the string_list. Integer_list = list(map(int, string_list)) Finally, we print the contents of integer_list. The resulting list of integers is stored in the variable integer_list. And as we can observe, typecasting the string using the list () method gives us a list of the member characters, as required. To convert a Python list to a string using list comprehension and the str () function, you can follow these steps: Create a list with elements: Start by defining a Python list containing the elements you want to convert to a string. The method returns the value you passed through int (), represented as an integer. int () takes in two parameters: the string to convert into an integer and the base you want your data to be represented in. We then use a list comprehension to loop through each element in the list and convert it to an integer using the int() function. Understanding the code: Firstly here, we initialize a string, string1 as AskPython and print its type using the type () method. Method 2: Using list comprehension and the str () function. The int () method can be used to convert a string to an integer value in Python. In the example, we create a list of strings called string_list. To convert a string list to an integer list in Python, you can use a list comprehension and the int() function to convert each string element into an integer. Converting a String List to an Integer List Using a list comprehension and the int() function In this article, you will learn how to convert a string list to an integer list in Python.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |