2011-11-15 85 views
0

我一直在阅读文件,我很难摆脱“\ t” 我试过使用i.strip().split("\t")[1]并将其附加到列表中。但如果连续那里有更多的标签它不是非常有用 例如: 如果我做我描述我得到Python:如何更改字符串或列表元素

z=['\t\t\t\twoman-in-lingerie', 'newspaper-photo', 'reference-to-marie-antoinette', '\tempty-grave', '\t\t\tbased-on-play', '\t\t\tcanadian-humor', '\t\t\tsitcom', 'hypocrisy', 'stripper'] 

现在我不知道如何删除这些标签,我一直试图让槽列表并改变自身的比特的每个元素它是不成功

+0

'strip()'移除多个标签没有问题。如果您的问题是将更改应用于多个列表项目,那么您应该这样说。显示你遇到问题的代码,而不仅仅是不需要的输出。 –

+0

如果没有人会看到它的危险,我会显示我的代码。 我正在做一个家庭作业,所有的程序显示相似性检查,如果发生这种情况我不能通过一个等级,因为我失去了我的机会进入考试 对不起 – buco

回答

2

如果你只是想删除选项卡,你可以使用这个列表理解:

l2 = [item.strip('\t') for item in l1] 

那将摆脱每个元素上的任何前导或尾随选项卡。

+0

谢谢你的这篇文章,也感谢其他两个,但你是一个有点太先进:) – buco

+0

@ buco - 乐于助人。如果您找到了答案,则需确保将其中一个标记为已接受。它有助于确保您继续获得高质量的答案并奖励帮助您的人。 –

2

如果你不希望任何选项卡,你可以阅读一切后,用filter

for item in my_list: 
    item = item.filter(lambda x: x != '\t', item) 
0

你能做的最好是使用replace功能,更换标签( '\ t')为空字符串( ''):

>>> z = ['\t\t\t\twoman-in-lingerie', '\t\t\tsitcom'] 
>>> map(lambda x: x.replace('\t',''), z) 
['woman-in-lingerie', 'sitcom'] 
0

这可能会给你一个想法:

>>> import re 
>>> re.sub('\t+','\t', 'hello\t\t\t') 
'hello\t' 
>>> 
0
z = '''\t\t\t\twoman-in-lingerie 
newspaper-photo\t\t\t\t   reference-to-marie-antoinette 
\tempty-grave 
\t\t\tbased-on-play 
\t\t\tcanadian-humor\t\t\t 
\t\t\tsitcom 
hypocrisy\t\t\t\t\tstripper''' 


import re 

def displ(x): 
    return '\n'.join(map(repr,x.splitlines(True))) 


print displ(z) 

print '-------------------------------' 
zt = re.sub('\t+',' ',z) 
print displ(zt) 

print '-------------------------------' 
zt = re.sub('(^\t+)|(\t+)', 
      lambda mat: '' if mat.group(1) else ' ', 
      z, 
      flags = re.MULTILINE) 
print displ(zt) 

print '-------------------------------' 
zt = re.sub('(^[ \t]+)|([ \t]+)', 
      lambda mat: '' if mat.group(1) else ' ', 
      z, 
      flags = re.MULTILINE) 
print displ(zt) 

结果

'\t\t\t\twoman-in-lingerie\n' 
'newspaper-photo\t\t\t\t   reference-to-marie-antoinette\n' 
'\tempty-grave\n' 
'\t\t\tbased-on-play\n' 
'\t\t\tcanadian-humor\t\t\t\n' 
'\t\t\tsitcom\n' 
'hypocrisy\t\t\t\t\tstripper' 
------------------------------- 
' woman-in-lingerie\n' 
'newspaper-photo   reference-to-marie-antoinette\n' 
' empty-grave\n' 
' based-on-play\n' 
' canadian-humor \n' 
' sitcom\n' 
'hypocrisy stripper' 
------------------------------- 
'woman-in-lingerie\n' 
'newspaper-photo   reference-to-marie-antoinette\n' 
'empty-grave\n' 
'based-on-play\n' 
'canadian-humor \n' 
'sitcom\n' 
'hypocrisy stripper' 
------------------------------- 
'woman-in-lingerie\n' 
'newspaper-photo reference-to-marie-antoinette\n' 
'empty-grave\n' 
'based-on-play\n' 
'canadian-humor \n' 
'sitcom\n' 
'hypocrisy stripper' 

我使用的功能显示终端()的方式来显示显示转义字符

相关问题