1

I have data like this:

0,tcp,http,SF,181,5450,0.11,0.00,0.00,0.00,,normal.
0,tcp,http,SF,239,486,0.05,0.00,0.00,0.00,normal.
0,tcp,http,SF,235,1337,0.03,0.00,0.00,0.00,normal.
0,tcp,http,SF,219,1337,0.03,0.00,0.00,0.00,normal.

The original data was stored in txt. I used list to store them in python. But the format is string. Then I want to change some columns of string into int like this:

'181' to 181

Could anyone can help me? Thank you!

song430
  • 11
  • 3
  • Possible duplicate of [How to convert string values to integer values while reading a CSV file?](https://stackoverflow.com/questions/33547790/how-to-convert-string-values-to-integer-values-while-reading-a-csv-file) – muru Oct 27 '17 at 02:41
  • Please provide your code – Vetsin Oct 27 '17 at 02:42
  • Possible duplicate of [How to convert strings into integers in Python?](https://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python) – James Oct 27 '17 at 02:42
  • Have you tried `int('181')`? – Dalton Cézane Oct 27 '17 at 02:42
  • Or https://stackoverflow.com/questions/11665628/read-data-from-csv-file-and-transform-to-correct-data-type fits more – muru Oct 27 '17 at 02:42
  • When saving to a file, you can not store strings and numbers separately. – 멍개-mung Oct 27 '17 at 02:54

2 Answers2

0

Showing how to

change some columns of string into int

with an example list :

>>> l = [['1','2','3'], ['4','5','6'], ['7','8','9']]

#based on index from 0
>>> row_to_change = 1

>>> [ int(row[row_to_change]) for row in l ]
    [2, 5, 8]

Now in case you want to change it in the list itself :

>>> for row in l :
        row[row_to_change] = int(row[row_to_change])

>>> l
[['1', 2, '3'], ['4', 5, '6'], ['7', 8, '9']]
Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
0
import re

fn = lambda i:float(i) if re.match('\d+(\.\d+)?',i) else i

with open('test.txt') as f:
    for line in f:
        line = list(map(fn,line.split(',')))
        print(line)



[0.0, 'tcp', 'http', 'SF', 181.0, 5450.0, 0.11, 0.0, 0.0, 0.0, '', 'normal.\n']
[0.0, 'tcp', 'http', 'SF', 239.0, 486.0, 0.05, 0.0, 0.0, 0.0, 'normal.\n']
[0.0, 'tcp', 'http', 'SF', 235.0, 1337.0, 0.03, 0.0, 0.0, 0.0, 'normal.\n']
[0.0, 'tcp', 'http', 'SF', 219.0, 1337.0, 0.03, 0.0, 0.0, 0.0, 'normal.']
Kobe Nein
  • 199
  • 1
  • 3
  • 13