Reputation: 89
I need to convert from string type to a number
list = ["-5","4","-3","variable"] # Input
list = [-5,4,-3,"variable"] # epected output
I have a problem when converting the negative number
list[0]=int(list[0])
ValueError: invalid literal for int() with base 10: '-5'
Upvotes: 6
Views: 46093
Reputation: 51
A solution is to use a regex to check if an element is a number. This is my example:
from re import match
ls = ["-5", "4", "-3", "variable"]
print([int(x) if match(r'^-?[0-9]+$', x) else x for x in ls])
Upvotes: 2
Reputation: 177
I encountered this problem in the matplotlib xticklabels Text attribute. The minus signs for negative numbers are encoded as a "minus":
[−] is a minus (Unicode 2212).
Minus: [&minus]; a.k.a. [−]; a.k.a. [−];
Python seems to code minuses as 'hyphen-minus', Unicode 002D:
[-] is a hyphen-minus (ASCII keyboard, Unicode 002D)
Hyphen minus: [-]; a.k.a. [-];
Here is an example:
>> import matplotlib.pyplot as plt
>> import re
>> x = [0,1,2,3,4,5]
>> y = [0,1,2,1,2,1]
>> fig,ax = plt.subplots(1)
>> plt.plot(x,y)
If we try to get at the xticklabels, if we want to manually edit them, we use:
>> l = ax.get_xticklabels()
>> ticks = [i.get_text() for i in l]
>> print(ticks)
['−1', '0', '1', '2', '3', '4', '5', '6']
>> ord(ticks[0])
8722
Try to convert it to an integer:
>> l = ax.get_xticklabels()
>> ticks = [int(i.get_text()) for i in l]
ValueError: invalid literal for int() with base 10: '−1'
This is the same error as in the question, which was difficult for others to recreate. To fix it, use regular expressions:
ticks = [int(re.sub(u"\u2212", "-", i.get_text())) for i in l]
print(ticks)
print(ticks[0] - 1)
[-1, 0, 1, 2, 3, 4, 5, 6]
-2
>> ord(ticks[0])
45
Upvotes: 9
Reputation: 1
follow this example.
list=[-1,2,'car']
convert=[]
for i in list.split():
if type(i) == str:
try:
convert.append(type(map(int,i)))
except ValueError:
convert.append(type(i))
return convert
Upvotes: 0
Reputation: 967
Actually, I cannot reproduce your error , it just work in python 2.7.13
>>>int("-5")
>>> -5
and in python 3.4
so, it could be a python version problem , I recommend updating your python version , by reinstalling the newer , from the site , it will replace it perfectly ( packages untouched ) , unless you are using , a special distribution like anaconda ..
for processing your list ( mixed chars and numbers ) use:
try: except:
statement.
Upvotes: 9
Reputation: 686
code you written above is working fine in python3
list1 = ["-5","4","-3","variable"]
list2 = []
print(list1)
for item in list1:
try:
list2.append(int(item))
except ValueError as e:
list2.append(item)
print(list2)
Output
['-5', '4', '-3', 'variable']
[-5, 4, -3, 'variable']
Upvotes: 0
Reputation: 137
I do not know how to replace values in a list, you will have to find that out for yourself. This code here
abc = "abcdefghijklmnopqrstuvwxyz" #to make sure there are no letters in the string
list = ["-5","4","-3","variable"]
def MightWork(list):
newlist = []
for item in list:
if set(abc) & set(list[item]) = False:
newlist.append(int(list[item]))
return newlist
list = MightWork(list)
might work. The reason why your code did not work is because you were changing the entire list into a string, not each individual item in the list. Knowing this, if you have any better solutions, try them.
Upvotes: 0