简体   繁体   中英

Convert string to negative number

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'

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.

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]; aka [&#8722]; aka [&#x2212];

https://en.wikipedia.org/wiki/Wikipedia:Hyphens_and_dashes

Python seems to code minuses as 'hyphen-minus', Unicode 002D:

[-] is a hyphen-minus (ASCII keyboard, Unicode 002D)

Hyphen minus: [&#45]; aka [&#x002D];

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

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.

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']

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM