0

Here I've got a string looks like that '128,120,119,118,119,118,120,116,116,120,128,121' I want to make it to be a list like this [128,120,119,118,119,118,120,116,116,120,128,121]

So I have ever tried a command 'list' in python to make it be a list

However, the result looks like that ['1', '2', '8', ',', '1', '2', '0', ',', '1', '1', '9', ',', '1', '1', '8', ',', '1', '1', '9', ',', '1', '1', '8', ',', '1', '2', '0', ',', '1', '1', '6', ',', '1', '1', '6', ',', '1', '2', '0', ',', '1', '2', '8', ',', '1', '2', '1'].

Although the type of the string data is list, the cutting point is wrong.

陳俊良
  • 319
  • 1
  • 6
  • 13

6 Answers6

3

Use Split method

>>> s = '128,120,119,118,119,118,120,116,116,120,128,121'
>>> l = s.split(',') # Split with ','
>>> [int(i) for i in l] # Change str to int type, *Used list comprehensions
[128, 120, 119, 118, 119, 118, 120, 116, 116, 120, 128, 121]
>>> 
ramganesh
  • 741
  • 1
  • 8
  • 33
2

The str.split() function will help here.

nums = '128,120,119,118,119,118,120,116,116,120,128,121'
num_list = nums.split(',')

The argument is how what character you want to split by.

PS. If you want to split by multiple characters, say in a string where the elements are separated by a comma and a space, like so nums = '128, 120, 119, 118, 119, 118, 120, 116, 116, 120, 128, 121', you can use nums.split(', ').

Yngve Moe
  • 1,057
  • 7
  • 17
1

You can use the split method for that.

my_string = "128,120,119,118,119,118,120,116,116,120,128,121"
my_list = my_string.split(",")

print my_list

Output:

['128','120','119','118','119','118','120','116','116','120','128','121']

Sasikumar Murugesan
  • 4,412
  • 10
  • 51
  • 74
subhead
  • 11
  • 1
1
a = '128,120,119,118,119,118,120,116,116,120,128,121'

b = [int(l) for l in a.split(',')]
Avijit Dasgupta
  • 2,055
  • 3
  • 22
  • 36
0

You can split on the basis of , to get a list as you need.

But keep in mind that that list be a list of strings i.e the number 128 will string '128'.

To get an integer list, you need to convert this string list to integer list.

You can do this like shown below.

num_string = '128,120,119,118,119,118,120,116,116,120,128,121'

string_list = num_string.split(',')

int_list = [int(x) for x in string_list]

print(int_list)
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
0

Add a simple statement:

d=[int(c) for c in b]

where b=['1','2',....]

MB11
  • 610
  • 1
  • 5
  • 16