如何使用python将字符串转换为列表

时间:2017-06-12 11:46:11

标签: python python-2.7

输入:

id int not 
null,
firstname char not 
null,

输出:

['id' 'int' 'not' 'null']
['firstname','char','not','null']

代码:

with open(file) as f:
    for line in f:
        x = line.split()
由于没有得到正确的输出,代码中缺少了一些东西

1 个答案:

答案 0 :(得分:0)

试试这个:

final_list = []
with open("wordchecking.txt", "r") as f:  # open your file
    for line in f:  # read it it line by line
        y = line.split()
        y = [z.replace(',','') for z in y]
        final_list.append(y)
for sub_list in final_list:
    print(sub_list)

因为你使用的是python 2:

print '[%s]' % ','.join(str(p) for p in sub_list)

输出:

['id', 'int', 'not', 'null']
['firstname', 'char', 'not', 'null']