-6

我有一个my_file包含两行的文件 ( ):

"002000", "WAYNE", "ROONEY", "M", 16SEP2012, 31DEC1977, 25OCT1968, 999999, "UK", "380", VOID;
"002001", "JOE", "COLE", "M", 16SEP2012, 31DEC1977, 13FEB1972, 999999, "UK", "390", VOID;

我愿意:

f = open(my_file)
lines = [line.strip() for line in f]
f.close()

for line in lines:
    print line
    print type(line)

print "------------------"
for line in lines:
    print line.strip(",")
    print type(line.strip(","))

在输出中:

"002000", "WAYNE", "ROONEY", "M", 16SEP2012, 31DEC1977, 25OCT1968, 999999, "UK", "380", VOID;
<type 'str'>
"002001", "JOE", "COLE", "M", 16SEP2012, 31DEC1977, 13FEB1972, 999999, "UK", "390", VOID;
<type 'str'>
------------------
"002000", "WAYNE", "ROONEY", "M", 16SEP2012, 31DEC1977, 25OCT1968, 999999, "UK", "380", VOID;
<type 'str'>
"002001", "JOE", "COLE", "M", 16SEP2012, 31DEC1977, 13FEB1972, 999999, "UK", "390", VOID;
<type 'str'>

list在第二个 for 循环中期望对象,因为我strip(",")在每一行都使用方法,但它仍然返回<type 'str'>。怎么了?

4

1 回答 1

6

str.strip删除环绕字符:

>>> ',,a,b,,'.strip(',')
'a,b'

用于str.split获取列表:

>>> 'a,b,c'.split(',')
['a', 'b', 'c']

>>> line = '"002000", "WAYNE", "ROONEY", "M", 16SEP2012, 31DEC1977, 25OCT1968, 999999, "UK", "380", VOID;"'
>>> [x.strip('" ') for x in line.split(',')]
['002000', 'WAYNE', 'ROONEY', 'M', '16SEP2012', '31DEC1977', '25OCT1968', '999999', 'UK', '380', 'VOID;']
于 2013-09-08T13:58:38.453 回答