New FAMILUG

The PyMiers

Monday 16 May 2016

[Python] convert string thành integer

Chả có gì để nói nếu chỉ có:

In [2]: [int(i) for i in ('1', '123', '1235')]
Out[2]: [1, 123, 1235]
Hàm int thậm chí còn biết cách làm sạch (strip) số trước khi convert:
In [3]: int('   5   ')
Out[3]: 5
Vậy convert 1 dạng string của 1 list số thành 1 list số thế nào:

In [4]: s = '[2, 3, 4, 123, 1235]'
In [5]: [int(i) for i in s[1:-1].split(',')]
Out[5]: [2, 3, 4, 123, 1235]
Và kiểm tra lại:
In [6]: s == str([int(i) for i in s[1:-1].split(',')])
Out[6]: True
Hay dùng assert để không thấy có exception nào được raise:
In [1]:  s = '[2, 3, 4, 123, 1235]'

In [2]: assert s == str([int(i) for i in s[1:-1].split(',')])

In [3]:

Written used Python3 + Ipython
Hết.
Inspired by +Đại Vũ Quang

3 comments:

  1. Kiểm tra lại dùng assert đi :D

    ReplyDelete
  2. Since YouTube has dedicated servers, you don't have to worry about the bandwidth and space. convert youtube videos

    ReplyDelete