How do I convert all strings in a list to integers?
['1', '2', '3'] ⟶ [1, 2, 3]
Given:
xs = ['1', '2', '3']
Use map then list to obtain a list of integers:
list(map(int, xs))
In Python 2, list was unnecessary since map returned a list:
map(int, xs)
Use a list comprehension on the list xs:
[int(x) for x in xs]
e.g.
>>> xs = ["1", "2", "3"]
>>> [int(x) for x in xs]
[1, 2, 3]
There are several methods to convert string numbers in a list to integers.
In Python 2.x you can use the map function:
>>> results = ['1', '2', '3']
>>> results = map(int, results)
>>> results
[1, 2, 3]
Here, It returns the list of elements after applying the function.
In Python 3.x you can use the same map
>>> results = ['1', '2', '3']
>>> results = list(map(int, results))
>>> results
[1, 2, 3]
Unlike python 2.x, Here map function will return map object i.e. iterator which will yield the result(values) one by one that's the reason further we need to add a function named as list which will be applied to all the iterable items.
Refer to the image below for the return value of the map function and it's type in the case of python 3.x
The third method which is common for both python 2.x and python 3.x i.e List Comprehensions
>>> results = ['1', '2', '3']
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
You can easily convert string list items into int items using loop shorthand in python
Say you have a string result = ['1','2','3']
Just do,
result = [int(item) for item in result]
print(result)
It'll give you output like
[1,2,3]
If your list contains pure integer strings, the accepted answer is the way to go. It will crash if you give it things that are not integers.
So: if you have data that may contain ints, possibly floats or other things as well - you can leverage your own function with errorhandling:
def maybeMakeNumber(s):
"""Returns a string 's' into a integer if possible, a float if needed or
returns it as is."""
# handle None, "", 0
if not s:
return s
try:
f = float(s)
i = int(f)
return i if f == i else f
except ValueError:
return s
data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]
converted = list(map(maybeMakeNumber, data))
print(converted)
Output:
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
To also handle iterables inside iterables you can use this helper:
from collections.abc import Iterable, Mapping
def convertEr(iterab):
"""Tries to convert an iterable to list of floats, ints or the original thing
from the iterable. Converts any iterable (tuple,set, ...) to itself in output.
Does not work for Mappings - you would need to check abc.Mapping and handle
things like {1:42, "1":84} when converting them - so they come out as is."""
if isinstance(iterab, str):
return maybeMakeNumber(iterab)
if isinstance(iterab, Mapping):
return iterab
if isinstance(iterab, Iterable):
return iterab.__class__(convertEr(p) for p in iterab)
data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed",
("0", "8", {"15", "things"}, "3.141"), "types"]
converted = convertEr(data)
print(converted)
Output:
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed',
(0, 8, {'things', 15}, 3.141), 'types'] # sets are unordered, hence diffrent order
A little bit more expanded than list comprehension but likewise useful:
def str_list_to_int_list(str_list):
n = 0
while n < len(str_list):
str_list[n] = int(str_list[n])
n += 1
return(str_list)
e.g.
>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]
Also:
def str_list_to_int_list(str_list):
int_list = [int(n) for n in str_list]
return int_list
Here is a simple solution with explanation for your query.
a=['1','2','3','4','5'] #The integer represented as a string in this list
b=[] #Fresh list
for i in a: #Declaring variable (i) as an item in the list (a).
b.append(int(i)) #Look below for explanation
print(b)
Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).
Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.
Output console:
[1, 2, 3, 4, 5]
So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.
You can do it simply in one line when taking input.
[int(i) for i in input().split("")]
Split it where you want.
If you want to convert a list not list simply put your list name in the place of input().split("").
I also want to add Python | Converting all strings in list to integers
Method #1 : Naive Method
# Python3 code to demonstrate
# converting list of strings to int
# using naive method
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using naive method to
# perform conversion
for i in range(0, len(test_list)):
test_list[i] = int(test_list[i])
# Printing modified list
print ("Modified list is : " + str(test_list))
Output:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
Method #2 : Using list comprehension
# Python3 code to demonstrate
# converting list of strings to int
# using list comprehension
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using list comprehension to
# perform conversion
test_list = [int(i) for i in test_list]
# Printing modified list
print ("Modified list is : " + str(test_list))
Output:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
Method #3 : Using map()
# Python3 code to demonstrate
# converting list of strings to int
# using map()
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using map() to
# perform conversion
test_list = list(map(int, test_list))
# Printing modified list
print ("Modified list is : " + str(test_list))
Output:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
The answers below, even the most popular ones, do not work for all situations. I have such a solution for super resistant thrust str.
I had such a thing:
AA = ['0', '0.5', '0.5', '0.1', '0.1', '0.1', '0.1']
AA = pd.DataFrame(AA, dtype=np.float64)
AA = AA.values.flatten()
AA = list(AA.flatten())
AA
[0.0, 0.5, 0.5, 0.1, 0.1, 0.1, 0.1]
You can laugh, but it works.
I have a list of float numbers (appear as strings) and NaN values.
import numpy as np
mylist = ['1.0', '0.0', np.nan, 'a']
I need to convert float string values into integer string values, while ignoring the rest of records:
mylist = ['1', '0', np.nan, 'a']
How can I do it?
I wrote the following code, but I don't know how to handle the exceptions np.nan, a, etc.
mylist2 = []
for i in mylist:
mylist2.append(str(int(float(n))))
You can use a map that calls a function to convert them to ints:
def to_int(x):
try:
x = str(int(float(x)))
except:
pass
return x
np.array(list(map(to_int, mylist)), dtype=object)
# array(['1', '0', nan, 'a'], dtype=object)```
Although there are different ways to achieve this. but let's go your way.
This might help.
mylist2 = []
for i in mylist:
try:
mylist2.append(str(int(float(n))))
except:
pass
Assuming you want to just use the original values when they are not numeric strings that can be converted to integers, you can write a helper function to try doing the conversion, and return the original value if an exception is raised.
def try_int(s):
try:
return str(int(float(s)))
except:
return s
mylist2 = [try_int(s) for s in mylist]
Be aware that the conversion from a float string to an int can sometimes make the strings much longer; for example, the string '9e200' will be converted to an integer string with 201 digits.
After reading the file directory using this line,
x = glob.glob('**/*.txt', recursive = True)
I got this output,
doping_center9_2.txt
doping_center9_3.txt
doping_center9_4.txt
doping_center9_5.txt
n_eff_doping_center1_1.txt
n_eff_doping_center1_2.txt
n_eff_doping_center1_3.txt
n_eff_doping_center1_4.txt
Now, I would like to create another list and appending the strings with a starting with n_eff. I tried this:
n_eff = []
for i in range(len(x)):
if x[i] == x[i].startswith("n_eff"):
n_eff.append(x[i])
Unfortunately, nothing is happening there, not even an error.
The problem is that startswith is returning boolean value (True or False). You are then checking if x[i] is equal to a boolean value which is always false because it contains string.
Changing the condition should help:
if x[i].startswith("n_eff"):
If the output is multiline you need to split it with split('\n').
Function "<string>".startswith(<arg>) returns True if <string> starts with the parameter string <arg>. You can check if a string starts with the specified sub string with this function.
Using list comprehension it can be written as:
new_list = [x for x in output if x.startswith('\n')]
edited considering output a list.
In [51]: x = '''doping_center9_2.txt
...: doping_center9_3.txt
...: doping_center9_4.txt
...: doping_center9_5.txt
...: n_eff_doping_center1_1.txt
...: n_eff_doping_center1_2.txt
...: n_eff_doping_center1_3.txt
...: n_eff_doping_center1_4.txt
...: '''.splitlines()
In [52]: x
Out[52]:
['doping_center9_2.txt',
'doping_center9_3.txt',
...
'n_eff_doping_center1_4.txt']
Are you trying to do something like this?
In [53]: for i in x:
...: if i.startswith('n_eff'):
...: print(i)
...:
n_eff_doping_center1_1.txt
n_eff_doping_center1_2.txt
n_eff_doping_center1_3.txt
n_eff_doping_center1_4.txt
How do I append two digit integer into a list using for loop without splitting them. For example I give the computer 10,14,13,15 and I get something like 1,0,1,4,1,3,1,5. I tried to go around this, but I ended up with a new issue, which is Type Error: sequence item 0: expected string, int found
def GetNumbers(List):
q=[]
Numberlist = []
for i in List:
if i.isdigit():
q.append(int(i))
else:
Numberlist.append(''.join(q[:]))
del q[:]
return Numberlist
Ideal way will be to use str.split() function as:
>>> my_num_string = "10,14,13,15"
>>> my_num_string.split(',')
['10', '14', '13', '15']
But, since you mentioned you can not use split(), you may use regex expression to extract numbers from string as:
>>> import re
>>> re.findall('\d+', my_num_string)
['10', '14', '13', '15']
Else, if you do not want to go with any fancy method, you may achieve it with simple for loop as:
num_str, num_list = '', []
# ^ Needed for storing the state of number while iterating over
# the string character by character
for c in my_num_string:
if c.isdigit():
num_str += c
else:
num_list.append(num_str)
num_str = ''
The numbers in num_list will be in the form of str. In order to convert them to int, you may explicitly convert them as:
num_list = [int(i) for i in num_list] # OR, list(map(int, num_list))
I am new to Python. I need to know how to convert a list of integers to a list of strings. So,
>>>list=[1,2,3,4]
I want to convert that list to this:
>>>print (list)
['1','2','3','4']
Also, can I add a list of strings to make it look something like this?
1234
You can use List Comprehension:
>>> my_list = [1, 2, 3, 4]
>>> [str(v) for v in my_list]
['1', '2', '3', '4']
or map():
>>> str_list = map(str, my_list)
>>> str_list
['1', '2', '3', '4']
In Python 3, you would need to use - list(map(str, my_list))
For 2nd part, you can use join():
>>> ''.join(str_list)
'1234'
And please don't name your list list. It shadows the built-in list.
>>>l=[1,2,3,4]
I've modified your example to not use the name list -- it shadows the actual builtin list, which will cause mysterious failures.
Here's how you make it into a list of strings:
l = [str(n) for n in l]
And here's how you make them all abut one another:
all_together = ''.join(l)
Using print:
>>> mylist = [1,2,3,4]
>>> print ('{}'*len(mylist)).format(*mylist)
1234
l = map(str,l)
will work, but may not make sense if you don't know what map is
l = [str(x) for x in l]
May make more sense at this time.
''.join(["1","2","3"]) == "123"