0

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

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从列表中删除?

4

2 回答 2

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']

此致 :)

于 2013-05-28T08:30:27.750 回答
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']
于 2013-05-28T08:32:41.013 回答