剥离后仍保留“\ t”符号

时间:2013-05-17 11:41:10

标签: python tabs

我有一个字符串和一些代码来剥离它:

def break_words(stuff):
words = stuff.split(' ')
return sorted(words)
sentence = 'All god'+"\t"+'things come to those who weight.'
print sentence#works as expected
words = break_words(sentence)
print words
按预期打印

sentence(不带\t符号);但words打印为:

['All', 'come', 'god\tthings', 'those', 'to', 'weight.', 'who']

如何从列表中删除\t

2 个答案:

答案 0 :(得分:1)

您可以使用.replace('\t',' ').expandtabs()

然后输入的所有新标签字符都将更改为空格。

试试这个

def break_words(stuff):
    words = stuff.replace('\t','').split(' ')
    return sorted(words)

sentence = 'All god'+"\t"+'things come to those who weight.'
print sentence#works as expected
words = break_words(sentence)
print w

输出:

All god things come to those who weight.
['All', 'come', 'godthings', 'those', 'to', 'weight.', 'who']

或者

def break_words(stuff):
    words = stuff.replace('\t',' ').split(' ')
    return sorted(words)

sentence = 'All god'+"\t"+'things come to those who weight.'
print sentence#works as expected
words = break_words(sentence)
print words

输出:

All god things come to those who weight.
['All', 'come', 'god', 'things', 'those', 'to', 'weight.', 'who']

最诚挚的问候:)

答案 1 :(得分:1)

sentence = 'All god'+"\t"+'things come to those who weight.'
words = sentence.expandtabs().split(' ')
words = sorted(words)
>> ['All', 'come', 'god', 'things', 'those', 'to', 'weight.', 'who']

或者您可以直接将其包裹在sorted()

words = sorted(sentence.expandtabs().split(' '))
>> ['All', 'come', 'god', 'things', 'those', 'to', 'weight.', 'who']