我有一个字符串和一些代码来剥离它:
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
?
答案 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']