-2

i have a problem if i have a string list

for example :

token=[aaa,bbb,ccc,ddd,0,eee,40,ggg,5]

how can i do to check whether token[i] is an integer

i want to see if token[i] is integer

i will put it in to a new string list by i+1:number

ex if token[4]=0 i will put it into result[5]="5:0"


sorry for explain not clear first if i have many data ex 39, State-gov, 77516, Bachelors, 13, Never-married, Adm-clerical, Not-in-family, White, Male, 2174, 0, 40, United-States, <=50K 50, Self-emp-not-inc, 83311, Bachelors, 13, Married-civ-spouse, Exec-managerial, Husband, White, Male, 0, 0, 13, United-States, <=50K

second i need to convert those data into specific number ex State-gov into 2:1 Self-emp-not-inc into 2:2

however i can convert string into number but i cannot convert number into number ex if token[4]=0 i will put it into result[5]="5:0"

for line in lines:
    token=re.split(', ',line)

  for i in range(0,13,1):
    try:
        value = int(token[i])

    except ValueError:
        pass  
    if (token[14] in '<=50K.'):
        result.append('1')
    if (token[14] in '>50K.'):
        result[j].append('2')
    if (value == true):
        result.append('i+1:token[i]')
    if (token[i] in '?'):
        result.append('i+1:0')
    if(token[i] in 'State-gov'):
        result.append("2:1")
    if(token[i] in 'Self-emp-not-inc'):
        result.append('2:2')
jackson
  • 23
  • 3
  • I dont think that this question is a duplicated !!! – Mazdak Nov 15 '14 at 09:04
  • I agreed 100%, this is a totally different question. At first I thought, "What, is it really possible that Python is so lame that all the elements of an array have to be of the same type, like original BASIC??!" That's the only way I could explain why someone would think a question asking how to determine if an array element is an integer is the same question as how to check if a string can be represented by a number. Thankfully, [it's not](http://stackoverflow.com/q/11387752/1248365). I'm voting to reopen. – Adi Inbar Nov 20 '14 at 04:16

3 Answers3

0

the function type, returns the type of the object

>>> type(10)
<type 'int'>
>>> type("10")
<type 'str'>
theAlse
  • 5,577
  • 11
  • 68
  • 110
0
>>> "13".isdigit()
True
>>> 
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
0

You need to use isinstance if you want to check the type of entry , and if you have multitype elements in your list :

>>> token=['aaa','bbb','ccc','ddd',0,'eee',40,'ggg',5]
>>> ["{}:{}".format(i,j) for i,j in enumerate(token,1) if isinstance(j,int)]
['5:0', '7:40', '9:5']
Mazdak
  • 105,000
  • 18
  • 159
  • 188